HTTP POST request works with Postman but not with my web application's JavaScript fetch

1.5k views Asked by At

I have a test environment in which I develop a website. This JavaScript code gives an error "415 unsupported media".

const sendData = async ()  => {
const result = await fetch(`${databaseURL}/categories`, {
    method: 'POST',
    headers: new Headers({
        accept: 'application/json',
        'contet-type': 'application/json'
    }),
    body: {"Name":"", "isHTTPS":0, "DisplayName":""}
});
const json = await result.json();

Works fine with Postman. And GET request do actually work in the web application. Tryed several things like adding "no-cors" to the header and stringifying the body. Same result. For my backend I am running a .NET C# application. I may have missed something. Can you help me? What additional information do you need for investigating my problem?

Thank you.

1

There are 1 answers

0
Emiel Zuurbier On

Notice the misspelled Content-Type header.

Your fetch function is saying it's sending JSON, but you still have to actually send JSON for the receiving end to decode it. Use JSON.stringify() to turn your body object into JSON before sending it.

const result = await fetch(`${databaseURL}/categories`, {
    method: 'POST',
    headers: new Headers({
        accept: 'application/json',
        'Content-Type': 'application/json'
    }),
    body: JSON.stringify({
      "Name": "", 
      "isHTTPS": 0, 
      "DisplayName": ""
    })
});