node.js - axios没有检索cookie

标签 node.js reactjs cors

嘿,我有一个问题,当我在本地运行服务器和应用程序时没有问题,但是当每个都被推送到各自的服务器时,应用程序不会返回 cookie。有谁知道如何解决这个问题?

服务器:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  next();
});

react :

const request = axios.post(`${url}/api/login`, {
      email,
      password,
      withCredentials: true,
      headers: { crossDomain: true, 'Content-Type': 'application/json' },
    })
    .then(response => response.data);

最佳答案

我想出了解决这个问题的方法。我用过:

服务器:

app.use(
  cors({
    credentials: true,
    origin: 'http://myapp.com',
  })
);

react :

export function loginUser({ email, password }) {
  axios.defaults.withCredentials = true;
  const request = axios
    .post(`${url}/api/login`, {
      email,
      password,
      withCredentials: true,
      headers: { crossDomain: true, 'Content-Type': 'application/json' },
    })
    .then(response => response.data);

  return {
    type: 'USER_LOGIN',
    payload: request,
  };
}

关于node.js - axios没有检索cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52684058/

相关文章:

node.js https没有响应 'end'事件, 'close'代替?

node.js - 如何在所有路由文件中使用app.js变量?

javascript - 如何从 Node.js 中的 REST API 导出 GET 响应?

javascript - 样式组件和 Webpack 5 联合模块之间的冲突(无效的钩子(Hook)调用)

http - Golang 重定向从 JS 调用 CORS 错误

c# - 选项预检未在 jQuery 中处理

node.js - node-sass-middleware 未编译

javascript - 将 LeafletJS 与 ReactJS 一起使用时,图 block 排序不正确

javascript - 我如何过滤数组并返回正确的属性?

rest - Wiremock CORS 不工作