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

  • 相关阅读:
    GIT和SVN之间的五个基本区别
    IOS多线程(NSThread,NSOperation,Grand Central Dispatch)
    MV*模型及部分vue
    你未必知道的49个CSS知识点--(转发地址)
    VUE增删改查
    动态树形菜单的几种递归写法小结
    vue-cli
    git的使用
    自动化构建工具----gulp
    前端包管理工具—bower
  • 原文地址:https://www.cnblogs.com/liujinyu/p/13514168.html
Copyright © 2011-2022 走看看