Fetch: How to use fetch post json and Sending cookies ?

Created on 15 Dec 2016  路  10Comments  路  Source: github/fetch

How are you.
I have a question: How to use fetch post json and Sending cookies ?
My code:

return fetch('/category/save.json' , {
            credentials: 'include',
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(function(response){
            if (response.status >= 200 && response.status < 300) {
                return response
            } else {
                var error = new Error(response.statusText);
                error.response = response;
                throw error
            }
        }).then(function(response) {
            return response.json();
        }).then(function(json) {
            console.log('parsed json', json)
        }).catch(function(ex) {            
            console.log('parsing failed', ex)
        });

Why cookie not send?
Thank you.

Most helpful comment

I only use parameter credentials: 'include' , The cookie Can send.
But I use parameter credentials: 'include' and headers: { 'Content-Type': 'application/json' } to post json data, Why cookie not send?

All 10 comments

I only use parameter credentials: 'include' , The cookie Can send.
But I use parameter credentials: 'include' and headers: { 'Content-Type': 'application/json' } to post json data, Why cookie not send?

Are you sending a request to another domain? See this note about CORS https://github.com/github/fetch#read-this-first

why & solution

cookie & Fetch & credentials

https://github.com/github/fetch#sending-cookies
https://github.com/github/fetch#receiving-cookies

image

why people answering question without watching closely to the question.

@kizzyang I find out what the problem is, change your params form

{ credentials: 'include', method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }

to

{ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, credentials: 'include', method: 'POST', body: JSON.stringify(data) }

@mislav this is a bug, you should fix it

@seajean if there is a bug, would you kindly please file a new issue that details the bug - including a code reproduction? That way we can address it much more quickly

@keithamus Sorry~ I finally found out it was Chrome鈥檚 problem,in some cases Chrome debugger do not show the cookie,but Charles do. The cookie has been sent.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

karladler picture karladler  路  4Comments

codeashian picture codeashian  路  3Comments

shirotech picture shirotech  路  3Comments

gkatsanos picture gkatsanos  路  4Comments

kocur4d picture kocur4d  路  3Comments