I'm working on something where I need to poll an http URL and get the numbers available as part of the response and show graphical stats on a web page.
Does anyone know of any opensource software which can do something like this?
Sample URL:
http://dataqueue.com:8080/datamq/message/getcount?q=order.sales&class=com.xyz.entitiy.Order&metadata={}
which Results 15000
then another url would result 10000 etc.
If I understand your question correctly, you can use plain Javascript to achieve something like this. Here's an example that does a server request every five seconds:
function req() {
fetch('http://reqres.in/api/users', {
method: 'post',
body: JSON.stringify({
name: 'morpheus',
job: 'leader'
})})
.then(res => res.json())
.then(json => {
document.getElementById('View').innerHTML = json.id;
});
}
req();
setInterval(() => req(), 5000);
<div id="View"></div>
There are also libraries that make this easier, for example PollJS. You can find more on Github. If you have control over the server, you might want to check out Socket.io.
Related
I am a university student and this is my first time of putting all together of server, api and client sides.
My problem is that first I have created an API using Django-Rest framework.
When I post data to that server using fetch function in JavaScript, it keeps posting that data and does not stop until I close. In the server database, many same data have been created.
I cannot figure out how to fix it. My intention was I want to post the data just once.
Please help me how to do it.
Thank you.
This is my javascript code ๐
const testPost = () => {
fetch('http://127.0.0.1:8000/mysite/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'player1Hp': 30,
'player2Hp': 20
})
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
.catch(error => console.log('ERROR'))
}
This is views.py in Django ๐
views.py photo
This is many POST messages in terminal cause of infinite looping ๐terminal photo
This is full screenshoot of script.js ๐ script.js photo
HTML just calls script and the rest is just blank. ๐ index.html photo
I'm trying to build a HTML, CSS, JS website and want to incorporate an API and use the response further in my website.
I've managed to make this API part work but I'm stuck with the final part.
What I've Achieved
Executing a JS function using FETCH that makes a POST Call with Auth Headers
Getting the response to show up inside my Chrome Developer Console.
What I'm trying to achieve
Use the Response (Web URL) that is being received by the POST API Call inside my
website as a variable. So when the user hits a button this response (URL) opens up in
a new tab.
In simple terms, I want the make use of the web url that shows up in the Chrome Console.
Here is the code I'm using
function initiateIDV(){
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Basic xxxxxxxxxxxxx");
var raw = JSON.stringify({
"customerInternalReference": "Will's App",
},
"userReference": "test-app",
"tokenLifetime": "10m"
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://[hidden]/api/v1/accounts", requestOptions)
.then(response => response.json())
.then(result => console.log(result.web.href))
.catch(error => console.log('error', error));
}
View From the Chrome Console of a Successful Response
I think there are 2 things to check first before make sure the value show in the Console.
Network request. Check in the Network panel to see if the network request call successful? If it's not fix the url or the API. Learn inspect network request
Log the result. Log the result object first to see if it contains .web.href. If it's not, fix the API.
I create a working example from your code. Run it and you will see result. I changed the API url to a demo url
function initiateIDV(){
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Basic xxxxxxxxxxxxx");
// changed body content
var raw = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
})
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
// changed url
fetch("https://jsonplaceholder.typicode.com/posts", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
initiateIDV();
Let me paraphrase your question. You want to:
make a POST request to an API
handle the API response in your JavaScript code
open a new tab in the user's browser, at the URL contained in the API response
And you are stuck at step 3.
What you are trying to achieve at step 3 is an effect (aka a side effect) on the user's browser.
Also, a minor remark about the terminology you used:
So when the user hits a button this response (URL) opens up in a new tab.
In your example the response is not a URL. You are calling response.json(), so the API response is JSON.
You are already performing a side effect at step 3: console.log(). A lot of stuff is a side effect. Basically everything that changes some kind of state. Printing something in the browser's console, showing an alert dialog, adding/removing CSS classes, adding/removing/altering DOM elements, are all side effects.
The side effect you want to achieve here is to open a new tab in the user's browser. In JS you can do it using this code:
window.open("https://stackoverflow.com/", '_blank').focus()
The state in your scenario is the fact that the browser currently has N tabs open, and after window.open() will have N+1 tabs open. And not only that. Opening a tab in Chrome might spawn a new operating system process (before the relationship was 1 tab => 1 process, but nowadays I don't think so, see here).
Basically I'm trying to have the user be able to input something into a form, for it to be sent back to the server so I can then process it and then send back a response that updates the DOM to show the result. I've tried figuring out jQuery and cheerio but I'm just confused and not sure exactly how I can do what I want
i think you must make HTTP Request POST to finish it, i have an article that can guide you, and i hope it helps
https://www.freecodecamp.org/news/here-is-the-most-popular-ways-to-make-an-http-request-in-javascript-954ce8c95aaa/
Just to get you started:
let data = Object.fromEntries(new FormData(document.querySelector("form")))
fetch(url, {
body: JSON.stringify(data)
}).then(r => r.json().then(responseData => {
document.querySelector("p").innerText = responseData.message
}))
Then you have to work out the backend code and adjust what I posted here to suit your needs.
I don't have much experience with React or JavaScript. I am creating a simple application that fetches time series data from an API. The data is used to plot a line chart (React Apex Chart). All good.
The problem is that the API response size is limited to a maximum of 2,000 records, and sometimes we need more data.
The API documentation says:
The response size is limited to a maximum of 2,000 records. If more records have to be returned, the response header contains a Link header with a URI to get the next set of records:
Link: https://apiurl; rel="next"
My Fetch Code:
My code fetches the api data, sorts it and sends it to the child component(Chart).
FetchAPI(){
fetch(https://MYURLHERE?from=FROMDATE&to=TODATE)
.then(response => response.json())
.then(data => this.setState({
kWhData: data.map((kWh) => kWh._kWh),
TimeStampData: data.map((time) => time._time),
loading: false
}))
.catch(error => console.log('Fetching failed', error))
}
Link header: linkย โ<https://MYURLHERE?from=FROMDATE&limit=2000&to=TODATE>; rel="next">
I know the solution may be some kind of pagination but I do not fully understand this concept. I have searched for similar problems with no luck.
Hope someone could provide me with a helping hand, tips or code.
I don't know what API you're using, but it sounds like all you need to do is get the URL to the next set of results from the headers and then make a request to that.
Before you return response.json(), you can access the headers with response.headers.get(). So you can do something like let nextPage = response.headers.get('Link') to get that full Link header as a string. Then you can split it at the semicolon and use the first part as the URL for the next paginated request.
If I've understood the question correctly, I would add a variable to your FetchApi function, so that it can query either your initial API URL, or the URL for a subsequent page:
FetchAPI(requestURL){
// Fetch function here
}
The idea is that this function can then call itself iteratively, with the url of the โnextโ page of results passed as a parameter for each call, until the response indicates all the data has been retrieved.
So your initial call would be FetchAPI('https://MYURLHERE?from=FROMDATE&to=TODATE').
You can then add a line to call this function again if the rate limit is reached. E.g:
FetchAPI(requestURL){
fetch(requestURL)
.then(response => {
if(response.dataLimit == true){ // Or however this is expressed
// Concat new data with any already retrieved
this.FetchAPI(nextPageUrl) // Get the URL of the next page and call FetchAPI again with this e.g https://MYURLHERE?from=FROMDATE&limit=2000&to=TODATE
} else {
// Otherwise stop and do something else now that you have a complete set of data
}
})
}
Worth saying that this is untested code, but hopefully enough to get the principle across.
Also if the API has a request rate limit e.g. 1 second, you could add a delay before the function calls itself again, though obviously this will impact the overall time to retrieve all of the data.
Thank you all. I got it to work with a mix of both answers.
I do not know if this is a good way to do it or the "right" approach. Maybe you guys could give me some feedback?
The setTimeout was just for testing, but I think I need to have minimum 1000?
The credentials/header is necessary to get the API.
FetchAPI(requestURL) {
fetch(requestURL, {
credentials: 'include',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"x-xsrf-token": this.myXRSFToken,
"origin": `${window.location.protocol}//${window.location.host}`
}
})
.then(response => {
let Responseheader = response.headers.get('Link')
response.json()
.then(data => this.setState({
TestData: this.state.TestData.concat(data)
}))
if (Responseheader){
let nextPageUrl = Responseheader.match(/\bhttps?:\/\/\S+Z/gi)
setTimeout(() => {
this.FetchAPI(nextPageUrl)
}, 2000);
} else {
console.log('Done fetching API')
this.setState({
loading: false
})
return
}
})
.catch(error => console.log('Fetching failed', error))
}
I'm using Sb-Admin-React. I need to make API call (CRUD) on this framework (Sb-Admin-React), but I have no idea to make it.
May there's anyone can help me to make it out. Thanks
Isomorphic fetch is already included in Sb-Admin-React.
You can make your regular API calls with fetch. It should look something like:
fetch(apiUrl, {
method: method,
headers: headersIfAny,
body: theDataToSend
})
.then(response => /* do something with response */)
.catch(err => /* do something with err */);
You can go through Isomorphic Fetch readme for more info