Fetch: JSON text/plain

Created on 11 Oct 2016  路  5Comments  路  Source: github/fetch

Seems that "Post JSON" don't work. Because if body is string (and JSON is actually a string) polyfill sets header 'content-type' to 'text/plain;charset=UTF-8'

But in docs:

fetch('/users', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
})

Most helpful comment

You seem to be sending a POST to another domain. Please familiarize yourself with CORS to learn what's blocking you from changing the Content-Type of the request.

All 5 comments

@shapkarin What exactly about posting JSON doesn't work? Our example suggests that you need to explicitly state content-type via header, because as you've noticed, the default content-type will not be correct for JSON.

If you're using our example code exactly as written, then please post the browser and the exception that you're getting. If you are experiencing failures in your own code, then please post example of that code.

Hello , Same here the server didn't get the json body

fetch('/main/newuser',{
            method:'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body:JSON.stringify({username:'test',password:'test'})
        }).then((response)=>{
            if(response.status >= 200 && response.status < 300){
                return response;
            }else{
                var error = new Error(response.statusText);
                error.response = response;
                throw error;
            }
        }).then((response)=>{
            return response.json();
        }).then((data)=>{
            /* Process data */
        }).catch((error)=>{
            /* Catch Error */
        });

code

const options = {
  mode: 'no-cors', // I just add that
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=utf-8'
  },
  body: JSON.stringify(post_body),
};

let test = async () => {
  let resp = await fetch(__url_guest, options);
  console.log(resp);
};
test();

console says

POST http://awsome.url 415 (Unsupported Media Type)

headers in request

content-type:text/plain;charset=UTF-8

You seem to be sending a POST to another domain. Please familiarize yourself with CORS to learn what's blocking you from changing the Content-Type of the request.

@mislav sorry, that was about server configuration. Fetch is a great way to write XHR :-)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

indranildutta06 picture indranildutta06  路  3Comments

ccorcos picture ccorcos  路  3Comments

poppinlp picture poppinlp  路  4Comments

mmocny picture mmocny  路  3Comments

proofrock picture proofrock  路  3Comments