问题
This is what my code looks like
let body = {
authCode: "XXXX",
clientId: "YYYYYY",
clientSecret: "ZZZZZZ"
};
fetch('https://api.myapp.com/oauth/token',{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
mode: 'no-cors',
body: body
}).then(function(response){
console.log("response: ", response);
}).catch(function(error){
console.log("could not get tokens: ", error);
})
In Chrome, this is what I see
I tried to do this by curl command and this is what it looks like
➜ ~ curl -X POST -H "Content-Type: application/json" -d '{
"authCode": "XXXX",
"clientId": "YYYYY",
"clientSecret": "ZZZZZZZZ"
}' https://api.myapp.com/oauth/token
{"authToken":"e141kjhkwr3432ca9b3d2128385ad91db4cd2:cca6b151-cab4-4de2-81db-9a739a62ae88:23000000"}
What am I doing wrong here?
UPDATE
After changing it to following, the result is still HTTP 415
fetch('https://api.myapp.com/oauth/token',{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
mode: 'no-cors',
body: JSON.stringify(body)
}).then(function(response){
console.log("response: ", response);
}).catch(function(error){
console.log("could not get tokens: ", error);
})
Interestingly, I realized that I sent the header "Content-Type": "application/json" while what I get back is content-type: text/plain, why that might be happening?
回答1:
fetch() does not expect a JavaScript object at body. curl command and fetch() pattern are not the same. Use body: JSON.stringify(<javascript plain object>).
Request
Note: The
bodytype can only be aBlob,BufferSource,FormData,URLSearchParams,USVStringorReadableStreamtype, so for adding aJSONobject to the payload you need to stringify that object.
See Fetch with ReadableStream for status of implementation of ReadableStream set as value for body.
回答2:
you must define Accept and Content-Type headers like that and stringify your data object
const params = {
headers: {
'Accept': "application/json, text/plain, */*",
'Content-Type': "application/json;charset=utf-8"
},
body: JSON.stringify(yourObject),
method: "POST"
};
fetch(url, params)
.then(data => { console.log('data', data)})
.then(res => { console.log('res', res) })
.catch(error => { console.log('error', error) });
来源:https://stackoverflow.com/questions/44192731/fetch-post-is-returning-http-415-while-curl-goes-on-fine-and-returns-result