zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Java加密与解密之非对称加密算法
    Java加密与解密之对称加密算法
    Java加密与解密之消息摘要算法
    基于Spring Cloud Zookeeper的服务注册与发现
    .NET 5.0正式发布,新功能特性(翻译)
    C# 9.0 中的新增功能
    C# 规范建议
    Flutter Weekly Issue 70
    Android 开发技术周报 Issue#298
    Flutter Weekly Issue 69
  • 原文地址:https://www.cnblogs.com/liujinyu/p/13514168.html
Copyright © 2011-2022 走看看