【发布时间】:2020-10-22 23:07:38
【问题描述】:
我有一个在 localhost:8181 运行的 ExpressJS 应用程序和一个在 localhost:3000 运行的 ReactJS。在我的 Express 应用程序中,我使用 cookie-session 来生成 cookie。 Express 应用如下所示:
const express = require('express');
const cookieSession = require('cookie-session');
const { v4: uuid } = require('uuid')
const app = express();
app.use(express.json())
app.use(cookieSession({
name: 'shortlinks',
keys: [process.env.SESHSECRET],
maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
}))
app.use(function(req, res, next) {
console.log(`${req.method} ${req.url}`);
req.session.id = (req.session.id || uuid());
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
next();
})
app.get(
'/api/links',
(req, res, next)=> {
res.json(readDb());
next();
}
)
在我的 React 应用程序中,我正在向 Express 应用程序发出简单的 GET 和 POST 请求。它们看起来像这样:
export async function getLink(id) {
const response = await fetch(`${LINKS_URL}/${id}`, { withCredentials: true, credentials: 'include' });
const json = await response.json();
return json;
}
export async function createLink(url) {
if (!url) return;
const response = await fetch(LINKS_URL, {
withCredentials: true,
credentials: 'include',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ long_url: url })
});
const json = await response.json();
return json;
}
在 Chrome 中,当我检查网络响应时,我看到响应标头中设置了 cookie:
Set-Cookie: shortlinks=eyJpZCI6IjkxNDg0MTFjLTI5MTAtNGQ5Ni04ZTdhLTZlMzAyZTQ4NzljNiJ9; path=/; expires=Sat, 21 Nov 2020 00:39:18 GMT; httponly
Set-Cookie: shortlinks.sig=kz0vL2oUQ9KYsDrROkLasxV762w; path=/; expires=Sat, 21 Nov 2020 00:39:18 GMT; httponly
X-Powered-By: Express
但是当我在 Chrome 中的应用程序 -> 存储 -> Cookies 下检查 cookie 时,我没有看到任何 cookie。
到目前为止我已经尝试过(这些都不起作用):
- 通过
127.0.0.1:3000而不是localhost:3000访问 React - 修改
/etc/hosts以将localhost映射到通用www.localexample.comURL - 在我的 React 应用中修改
fetchs(添加/删除/更改credentials和withCredentials参数) - 尝试其他浏览器
我还能尝试什么?我的想法已经用完了。
【问题讨论】:
标签: node.js reactjs express cookies