首页 > 解决方案 > React:CSRF Coo​​kie 在生产中未定义,在本地工作

问题描述

我将我的 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.jsreactjscookies

解决方案


推荐阅读