function fetchJSONFile(isRest, path, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('POST', path, true);
if (isRest) {
let mail = "***";
let pw = "***";
httpRequest.setRequestHeader("Authorization", "Basic " + window.btoa(mail + ":" + pw));
}
httpRequest.send("--data '[1, 2]'"); // also tried data=[1, 2]
}
I want to pass my data to the request, so that i'm able to get a response with the data i need. Currently i'm getting 415 error. What's wrong with my code?
Curl for api:
curl --user test@gmail.com:secret -X POST -H 'Content-Type: application/json' \
http://localhost:8888/api/quizzes/1/solve --data '[1, 2]'
According the curl, you need to also set as header the Content-Type
, it would look something like this:
httpRequest.setRequestHeader('Content-Type', 'application/json');
and then send with JSON.stringify method to make sure you send JSON in proper string format.
httpRequest.send(JSON.stringify({ myKey: 'myValue' });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.