Express doesn't set a cookie

后端 未结 10 1570
花落未央
花落未央 2020-12-14 01:45

I have problem with setting a cookies via express. I\'m using Este.js dev stack and I try to set a cookie in API auth /login route. Here is the cod

10条回答
  •  -上瘾入骨i
    2020-12-14 02:14

    I had the same issue. The server response comes with cookie set:

    Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT 
    

    But the cookie was not saved by a browser.

    This is how I solved it.

    I use fetch in a client-side code. If you do not specify credentials: 'include' in fetch options, cookies are neither sent to server nor saved by a browser, although the server response sets cookies.

    Example:

    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    
    return fetch('/your/server_endpoint', {
        method: 'POST',
        mode: 'same-origin',
        redirect: 'follow',
        credentials: 'include', // Don't forget to specify this if you need cookies
        headers: headers,
        body: JSON.stringify({
            first_name: 'John',
            last_name: 'Doe'
        })
    })
    

    Hope it helps somebody.

提交回复
热议问题