Search code examples
javascriptpostfetch

POST request works with curl and Postman, but fails with javascript fetch


I'm having this problem. I'm trying to fetch a POST request with javascript, but what I receive back is a 415 error:

const getToken = async () => {
const response = await fetch('https://thebetter.bsgroup.eu/authorization/signIn', {
    method: 'post',
    mode: 'no-cors',
    headers: {
        'Content-Type': 'application/json',
        accept: 'application/json',
    },
    body: {},
});
const data = response.json();
console.log(data);

};

With the below curl command I get the correct response. Same with Postman.

curl -X POST "https://thebetter.bsgroup.eu/Authorization/SignIn" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{}"

What's the problem here?


Solution

  • This is because you are using mode: 'no-cors'.

    For no-cors you can only perform this application-types posts:

    • text/plain
    • application/x-www-form-urlencoded
    • multipart/form-data

    Since you are trying to perform application/jsonthe browser is overwriting to text/plain.

    Do you have access to the server from thebetter.bsgroup.eu? If so, just remove the mode: no-cors from the request and add the 'Access-Control-Allow-Origin': [REQUEST'S-HOST].com to the response. Otherwise, you can't perform this operation due to security concerns.