Fetch POST returns HTTP 415 while curl goes fine and returns the result
This is how 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);
})
I tried to do it with curl command
and it looks like this:
➜ ~ 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 you changed it to the 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);
})
I wonder if I figured out I sent the header "Content-Type": "application/json"
while I get back content-type: text/plain
, why might this be happening?
source to share
fetch()
does not expect JavaScript object in body
. Command curl
and template fetch()
do not match. Use body: JSON.stringify(<javascript plain object>)
.
Note. Type
body
can only beBlob
,BufferSource
,FormData
,URLSearchParams
,USVString
orReadableStream
, so to add aJSON
facility to the payload required to create this object.
See Fetch with ReadableStream for implementation status ReadableStream
set to value for body
.
source to share