【发布时间】:2021-06-15 16:10:32
【问题描述】:
我正在使用带有 jwt 身份验证的 ReactJS 和 ExpressJS。在我的服务器中,我有这样的 cors 配置
const corsOptions = {
//To allow requests from client
origin: true,
credentials: true,
methods: ['GET', 'PUT', 'POST', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization', 'Set-Cookie'],
};
在我的客户端中,我像这样向服务器发送请求
export function createNewRequest(data, callback) {
axios.post(`${process.env.REACT_APP_API}/api/requests`, data,
{
withCredentials: true
}).then(res => {
callback(res.data);
})
.catch(err => {
if (err.response) {
if (err.response.status === 403 || err.response.status === 401) {
getToken(createNewRequest(data, callback));
} else {
callback(err.response.data);
}
}
})
}
在我的本地环境中,我进行了测试,一切都运行良好。但是当我部署我的服务器时,我尝试从本地客户端向服务器发送请求。服务器不会在标头中接收 cookie。
我试过像这样设置原点
const corsOptions = {
//To allow requests from client
origin: ['http://localhost:3000'],
credentials: true,
methods: ['GET', 'PUT', 'POST', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization', 'Set-Cookie'],
};
并尝试使用凭据设置默认值
axios.defaults.withCredentials = true;
但这些都不起作用。谁能向我解释我做错了什么并帮助我解决这个问题
【问题讨论】:
标签: reactjs express cookies axios cross-domain