node.js - React 不保留或发送 cookie 到 Node?

标签 node.js reactjs cookies postman

我有一个带有此简化 API 的 Node 应用程序,用于检查用户是否经过身份验证(通过 session ):

export default (req, res,) => {
  if (!req.session || !req.session.loggedIn) {
    return res.status(401).send();
  }
  return res.status(200).send();
};

在 Postman 中一切正常,但是当 React 客户端发出此请求时:

axios.get(`${domain}/is-auth`)
  .then((res) => {
    return res.status === 200;
  })
  .catch((err) => {
    throw err;
  });

...它总是得到 401 并返回 false。服务器看不到它的 session 。我正在阅读有关 cookie 的内容,但是 cookie 不是应该由浏览器自动保存和发送吗?如果不是那么我该怎么做?请帮忙。

最佳答案

fetchaxios实际上不会随请求自动发送凭据,您必须通过将“withCredentials”选项设置为 true 来指定它:

axios.get(`${domain}/is-auth`, { withCredentials: true })
  .then((res) => {
    return res.status === 200;
  })
  .catch((err) => {
    throw err;
  });

关于node.js - React 不保留或发送 cookie 到 Node?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57442931/

相关文章:

node.js - Sequelize 包括创建一个嵌套对象

node.js - 媒体播放器在 Google Assistant 上运行良好,而模拟器则不然

javascript - 如何使用 Material UI 将组件居中/右对齐?

javascript - 使用箭头函数 react this.setState 导致控制台出错

javascript - 如何从 typescript 中的扩展类中排除接口(interface)属性

javascript - 使用 URL 向 cookie 添加值

asp.net - .ASPXAUTH cookie 在 session 结束时过期

node.js - 如何使用 Sails.js、sails-mong 和 Mongo DB 重命名数据库架构中的所有字段

node.js - 在 Win ES 7 上使用 PM2 运行 node-red 时为 "SyntaxError: Invalid or unexpected token"

c++ - 如何在 ISAPI 过滤器中设置多个 cookie