I'm trying to Post against an API, It does work when I use Postman and attach all my data as "form-data".
When I try it with the js fetch method like this
const data = {
'client_id': 'lorem ipsum',
'client_secret': 'lorem ipsum',
'scope': 'lorem ipsum',
'grant_type': 'lorem ipsum'
};
fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
or like this:
const data = new FormData();
data.append('client_id', 'lorem ipsum');
data.append('client_secret', 'lorem ipsum');
data.append('scope', 'lorem ipsum');
data.append('grant_type', 'lorem ipsum');
fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: data
})
I get an invalid_request error back, so obviously the API is expecting the data to be something different, can anybody help me out how to transmit the data as formData in the fetch method as Postman for example does it?
The above error is commonly caused due to mismatch of content-type between what was supplied by fetch method and that expected by the server API.
In the above code, the fetch method is sending content of the type 'aplpication/json'.
If the server is throwing an error for this format, it can be concluded that the server is probably expecting content in a different format.
The valid content-type formats supported are:
Therefore, the problem may be solved by changing the 'content-type' header in the fetch call from 'application/json' to one of these other supported types.
An example of working fetch call:
const data = new FormData();
data.append('client_id', 'lorem ipsum');
data.append('client_secret', 'lorem ipsum');
data.append('scope', 'lorem ipsum');
data.append('grant_type', 'lorem ipsum');
fetch(apiUrl, {
method: "POST",
headers: {
// "Content-Type": "application/json" --> option 1 (not working)
// "Content-Type": "application/x-www-form-urlencoded" --> option 2
// "Content-Type": "multipart/form-data" --> option 3
// "Content-Type": "text/plain" --> option 4
},
body: data
})
// Option 5: Try fetch without any header
fetch(apiUrl, {
method: "POST",
body: data
})
More information:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch