I am attempting to make an api get request using JS's built in XMLHttpRequest system. I am not sure why this function fails to work.
function updateStats(username){
const request = new XMLHttpRequest;
var url = "https://pitpanda.rocks/api/players/" + username;
request.open("GET", url);
request.send();
request.onload = (e) => {
return request.response;
}
}
My code is running on CodePen right now https://codepen.io/casperqf/pen/NWXGeqa
I recommend using fetch. Allows you to set the method and some other values.
Can do with fetch and not with XHR:
You can use the API with the request and response objects.
You can perform no-cors requests, getting a response from a server that doesn't implement CORS. You can't access the response body directly from JavaScript.
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
function updateStats(username, stats){
postData('https://pitpanda.rocks/api/players/' + username, { stats: stats })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
}
updateStats('otik', 123);
Related
I have a problem in fetch data ?
in my header , i will send token for authentication to my back-end but i don't know how i can add header to get method ..
fetch('https://api.github.com/users/mralexgray/repos', {
method: 'GET',
header: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Aequseted-With": "XMLHttpRequest",
"Authorization": `Bearer ${token}`
}
}).then((result) => {
result.json()
console.log(result)
if (result.status == 200) {
async function GetLink() {
const response = await fetch('https://api.github.com/users/mralexgray/repos')
const data = await response.json();
console.log(data)
sessionStorage.setItem('userAttemps', data[0].id);
sessionStorage.setItem('freeAttemps', data[0].id);
}
GetLink()
}
}).catch(err => {
console.error(err);
});
userAttemps = sessionStorage.getItem('userAttemps')
freeAttemps = sessionStorage.getItem('freeAttemps')
Is my code correct?
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then((data) => {
console.log(data); // JSON data parsed by `data.json()` call
});
I am trying to build a frontend interface to communicate with an API service, I am using HTML,CSS & JavaScript. I am using async function / await fetch to call the API and response.jsom to retrieve the Json data from the response, now I have to add X-Authorization:Bearer Token '.....' to the header, how can I do that with JavaScript?
thanx for help
Add your token inside the header, here is an example, call this postData function anywhere from your application, you can add it in a common place
Also check
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
this for the detailed explanation
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
let token = "Get your token here, Store it in local storage and read it from local storage is a better method"
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
"X-Authorization":Bearer Token '.....' // Here you can add your token
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
How to set header and parameter for route.get in node js?
I want to set header value and parameter to API data call URL.
router.get("/getdata", async (req, res) => {
res.header({
'key': '123456'
});
await fetch(`https://example.com/api?param=${data}`)
.then((data) => data.json())
.then((data) => res.json({ msg: data }))
.catch((err) => console.log(err));
});
my question is how to set header and parameter data in router.get in node js ?
The question is not clear and you should add more details to it and ask the specific things which might be causing an issue.
Headers are set on the response which can be done directly on res object like this:
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})
Check this for more details.
If you need to set headers on fetch API call, You can do that directly on fetch as below:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
If you want to read params in the req object:
router.get("/getdata", async (req, res) => {
const query = req.query // its an object containing all the params
await fetch(`https://example.com/api?param=${data}`)
.then((data) => data.json())
.then((data) => res.json({ msg: data }))
.catch((err) => console.log(err));
});
Read the documentation for Express around routing. It explains on how to e.g. use req.query to access the param in that fetch URL.
I'm sending data to the server using JSON and post method, but I can't read the response from the server. Here's my code:
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://staging.smartenupcs.com/api/v1/licenses/create", true);
xhr.setRequestHeader("Smartenup-API-KEY", "webflow.c407d56c5ab23115af0075+DzDMrMtWZENCoct9Pa7DUA54mIgP8c9o");
var jsonStr = JSON.stringify({
"first_name": "Bla",
"last_name": "Blabla",
"email": "bla#gmail.com",
"product_name": "webflow_essentials",
"order_id": 21811,
"voucher": null
});
xhr.send(jsonStr);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var myObj = JSON.parse(xhr.responseText);
alert(myObj);
}
};
I tried many options but no success.
I hope someone can help, thank you in advance
There are no issues with the code.
The issue is with Cross-Origin Requests. You seems to be hitting API from domain other than staging.smartenupcs.com most probably localhost.
Just add cross-origin headers to server and it will work.
PS: It will work without cross-origin headers when your frontend code and api are hosted on same domain.
Please check at Server side for Access-Control-Allow-Origin header. Also check for OPTIONS preflight request of that api/action. After that check for api response status and your response checking condition.
I would recommend using fetch API instead of the XMLHttpRequest object.
function postData(url = `UR_URL_HERE`, data = {}) {
// Default options are marked with *
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json()); // parses response to JSON
}
I'm need send user data at request to my endpoint (rest api), but gets 401 error only if make request from the js side. If make request from Postman, I get 200 status. I did everything as in the documentation. for reference: make request from Nodejs. Thanks
var token = 'Token 897d3c9991952bc715fcf6c3e262e5b3866342';
var myHeaders = new Headers();
myHeaders.append('Authorization', token);
fetch(this.domain + '/v1.0/user/data/', {method: 'GET', headers: myHeaders, mode: 'no-cors'})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('error');
}
})
Check this link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch or you can use axios to make request.
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('http://<host>:<port>/<end-point>?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
fetch:
// Example POST method implementation:
postData(`http://<host>:<port>/<end-point>`, {answer: 42})
.then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
.catch(error => console.error(error));
function postData(url = ``, data = {}) {
// Default options are marked with *
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
headers: {
"Content-Type": "application/json; charset=utf-8",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json()); // parses response to JSON
}