Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Express Cookies未与Fetch一起存储_Express_Cookies_Fetch_Jwt_Redux - Fatal编程技术网

Express Cookies未与Fetch一起存储

Express Cookies未与Fetch一起存储,express,cookies,fetch,jwt,redux,Express,Cookies,Fetch,Jwt,Redux,我已经阅读了我能找到的关于这个问题的所有其他主题,但没有一个解决方案有效。我正在使用React+Redux+Express并尝试按照以下步骤将JWT存储在cookie中: 在我的Redux操作中,我发送以下请求: export function getCookie(token) { const config = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Auth

我已经阅读了我能找到的关于这个问题的所有其他主题,但没有一个解决方案有效。我正在使用React+Redux+Express并尝试按照以下步骤将JWT存储在cookie中:

在我的Redux操作中,我发送以下请求:

export function getCookie(token) {
  const config = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + token
    },
    body: JSON.stringify({ token })
  };
  return fetch('http://127.0.0.1:4000/authorize-cookie', config)
   .then((res) => {
     return res.json();
   })
   .then((resJson) => {
     return resJson;
   })
   .catch(err => console.log('Error: ', err));
}
在服务器上,我用

app.post('/authorize-cookie', authenticate, (req, res) => {
  res.cookie('id_token', req.body.token, {
    maxAge: 360000
  });
  res.status(200).send({ message: 'Cookie set!' });
});
…其中,authenticate是验证令牌的函数

我的回复标题似乎一切正常:

HTTP/1.1 200 OK
Set-Cookie: id_token=xxx.xxx.xxx; Max-Age=360; Path=/; Expires=Tue, 12 Jan 2016 01:24:03 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 25
ETag: W/"19-UA3htFr0PWczMQBN6T4NpA"
Date: Tue, 12 Jan 2016 01:18:03 GMT
Connection: keep-alive
但是当我检查sources选项卡时,没有找到cookie。我读过关于关闭httpOnly和secure以及使用localhost的问题。我也尝试了所有主要的浏览器,但没有成功


这是怎么回事?

你遇到了一个有趣的案例。问题是
fetch
函数的行为与
XMLHttpRequest
不同。要在
fetch
中使用cookie,您应该明确提供
凭证
选项

fetch('http://127.0.0.1:4000/authorize-cookie', {
    method: 'POST',
    body: JSON.stringify({token: token}),
    credentials: 'same-origin', // <- this is mandatory to deal with cookies
})
fetch('http://127.0.0.1:4000/authorize-曲奇'{
方法:“POST”,
body:JSON.stringify({token:token}),

凭据:'相同来源',//您的cookie具有
Max Age=360
(即6分钟).也许它过期太快了?我已经尝试过将它改为几小时几天,但仍然没有成功。正如我看到的,你将
http://127.0.0.1:4000
。它实际上是打开网页的同一个域吗?在跨源请求期间无法保存cookies。是的,它是同一个域。我甚至将其设置为允许跨源请求我一度试图确定那不是我的问题。