axios没有检索cookie

Posted

技术标签:

【中文标题】axios没有检索cookie【英文标题】:axios not retrieving cookie 【发布时间】:2019-03-12 01:11:44 【问题描述】:

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

【问题讨论】:

【参考方案1】:

我想出了如何解决这个问题。我用过:

服务器:

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

【讨论】:

它对我有用。即使没有 headers 选项也可以工作。【参考方案2】:

尝试使用默认值axios.defaults.withCredentials = true

这是一个已知的bug 与 axios

【讨论】:

谢谢,但我会把它放在哪里?在请求中? 只要放在请求前就可以了

以上是关于axios没有检索cookie的主要内容,如果未能解决你的问题,请参考以下文章

axios 不会从 django 服务器检索数据

ReactJs,如何给 Axios 我的令牌以从 API 检索数据

如何检索由axios post请求发送的php中的变量[重复]

Vue Axios 检索列表中对象的响应 ID

Laravel 5.7 - 如何使用 axios.get 从 API 检索数据?

Next Js - 如何从需要授权的api中检索数据(通过axios)?