node服务端设置跨域,以及为什么服务端设置了跨域,还是报跨域错误

拿express举例

// 配置允许跨域请求;
app.all('*', function(req, res, next) {  
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");  
  res.header("Access-Control-Allow-Credentials", "true");  
  res.header("Access-Control-Allow-Headers", "X-Requested-With");  
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
  res.header("X-Powered-By",' 3.2.1')  
  res.header("Content-Type", "application/json;charset=utf-8");  
  next();  
});

前后端分离的项目中肯定会碰到跨域的问题,究其原因还是为了安全。我在一个前端工程调试过程中发现,即使我后端已经允许了跨域,但是前端依然报一个跨域错误。

the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

 

Access-Control-Allow-Credentials 

这个是服务端下发到客户端的 response 中头部字段,意义是允许客户端携带验证信息,例如 cookie 之类的。这样客户端在发起跨域请求的时候,不就可以携带允许的头,还可以携带验证信息的头,

 

axios 客户端用axios,并且手残的设置了 withCredentials: true,意思是客户端想要携带验证信息头,但是我的服务端设置是 'supportsCredentials' => false, ,表示不允许携带信息头,好了,错误找到了。

我们的客户端和服务端交互的时候使用的是 token,通过 Authorization头发送到服务端,并没有使用到 cookie,所以客户端没有必要设置 withCredentials: true

posted @ 2020-08-16 20:51  刘金宇  阅读(1730)  评论(0编辑  收藏  举报