• 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

  • 相关阅读:
    2019高考数学理科Ⅱ卷解析版[解答题]
    对风说爱你
    佛教人生-伴侣
    【Echarts每天一例】-1
    算法中涉及的专业英语
    python--随机函数(random,uniform,randint,randrange,shuffle,sample)
    【linux shell系列--1】crontab命令
    【Python爬虫实战--3】html写正则表达式
    mysql启动参数 skip-grant-tables
    php通过反射执行某方法
  • 原文地址:https://www.cnblogs.com/liujinyu/p/13514168.html
Copyright © 2020-2023  润新知