axios无法检索cookie

马特

嘿,我遇到了一个问题,当我在本地运行服务器和应用程序时没有问题,但是当将它们分别推送到各自的服务器时,应用程序不会返回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();
});

反应:

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',
  })
);

反应:

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,
  };
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章