CORS跨域

一、修改代码:
1.简单请求
//go后端(w为http.ResponseWriter):
         w.Header().Set("Access-Control-Allow-Origin", “*”);

2.非简单请求(预检)
 //go后端(w为http.ResponseWriter):

         // 如果需要http请求中带上cookie,需要前后端都设置credentials,且后端设置指定的origin,即域名不能为"*"
         w.Header().Set("Access-Control-Allow-Origin", “http://192.168.20.203:8007”);
         w.Header().Set("Access-Control-Allow-Credentials", "true");
         w.Header().Set("P3P", "CP=CAO PSA OUR");
         // 非简单请求的CORS请求,会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求(preflight)
         // 这种情况下除了设置origin,还需要设置Access-Control-Request-Method以及Access-Control-Request-Headers
         w.Header().Set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
         w.Header().Set("Access-Control-Allow-Headers", "Origin,X-Requested-With, Content-Type,Accept,t");
         w.Header().Set("Access-Control-Max-Age", "120");//预检请求的有效期,单位为秒,在此期间不用发出另一条预检请求,为0则异步请求。
//前端axios:
         axios.defaults.withCredentials=true// 允许携带cookie
         axios.defaults.crossDomain=true//允许跨域但不携带cookie

参考链接:
1.https://segmentfault.com/a/1190000015597029
2.https://www.cnblogs.com/xjy20170907/p/12803175.html

二.nginx转发
location / {
    proxy_pass   http://ip:port;  #反向代理
    #当用 webpack-dev-server 等中间件代理接口访问 nignx 时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Credentials true;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    # ...
  }

上一篇:sharepoint获取exchange邮箱报错:该帐户无权模拟所请求的用户


下一篇:上传文件出现 413 Request Entity Too Large