node.js - React:CSRF Cookie 在生产中未定义,在本地工作
问题描述
我将我的 express API 托管在 AWS Elastic Beanstalk 上,并将我的客户端托管在 s3 云前端。当我将我的发布请求发送到本地登录端点时,我的 cookie 被定义并且路由工作。但是,当它在生产中时,cookie 总是返回 undefined 并且我的 API 超时。
请注意,cookie 正在从后端成功发送。我可以在开发工具中查看它。此外,cookies.get() 返回一个空对象。
我正在使用 CSURF 来表达 cookie。
以下是后端的附加代码:-
const csrfprotection = csrf({
cookie: true
})
app.use(csrfprotection)
//csrf protected
app.get('/csrf-token', (req, res) => {
res.cookie('XSRF-TOKEN', req.csrfToken())
return res.status(200).json({
message: "success",
})
});
以下是我的前端代码:-
const getCsrfToken = async () => {
try {
dispatch(fetchCsrfPending())
const result = await fetch("https:/api.example.com/csrf-token", {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: "include"
})
if (result.ok) {
let match = document.cookie.match(new RegExp('(^| )' + "XSRF-TOKEN" + '=([^;]+)'));
console.log(match) // ----> this returns null or undefined
if (match) {
dispatch(fetchCsrfSuccess(match[2]))
}
}
} catch (err) {
dispatch(fetchCsrfError({
error: err.message
}))
}
}
我无法理解出了什么问题,如果有人可以帮助我找到解决方案,我将不胜感激。
解决方案
推荐阅读
- node.js - 向数据库添加新记录时出现 UnhandledPromiseRejectionWarning
- java - 尝试启动活动时出现二进制 XML 运行时异常
- java - Why method that calls another one which throws RuntimeException needs return statement?
- matlab - Optimization problem - GlobalSearch is not generating initial vector in MATLAB
- django - 如何将多个字段数据列表与父模型一起发布到子模型
- laravel - Webpack - Use variable to compile
- fabricjs - 如何使用fabric.js为画布中的图像填充颜色
- c++ - 编译器优化消除了导致链接器错误的隐式模板实例化
- uwp - 如何在 UWP 中修复“没有任何空格的滑块刻度开始和结束位置”
- docker - 如何修复“错误:无效或损坏的 jarfile /root/.sbt/launchers/1.2.8/sbt-launch.jar”