Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

Converting this curl POST to a javascript POST with fetch or an XMLHttpRequest gives errors

I am working on making a POST from javascript. The POST in curl looks like this:

 curl -v -H "Content-Type: application/json" -X POST --data @local.json -u username:password https://example.com

However my attempts to do this in javascript have me at a full halt.

This is what I have tried so far:

fetch('https://example.com', {
method: 'POST',
headers: {
  'Content-Type': 'application/json',
  'Authorization': 'Basic username:password')),
},
body: data
}).then(response => console.log(response))
.catch(error => console.log('Authorization failed : ' + error.message));

And many variations of this

I have also tried using XMLHttpRequest

request.open('POST', 'https://example.com', true);
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'Basic username:password');
request.send(data);

request.onreadystatechange = function () {
    if (request.readyState === 4) {
       alert(request.responseText);
    }
};

mostly I get this error:

... has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

So I'd add all that and then it'd tell me there needed to be set-cookies but I'm already getting that from the sever when I do a curl so wth??

So that and 415. The more I look into it the deeper the rabbit hole goes. Some help would be really appreciated here.

I've read this: No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API It just confused me even more...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...