前端跨域

167 阅读1分钟

什么是跨域

  • 协议
  • 域名
  • 端口

为什么会报错

  • 浏览器安全检查
  • XHR请求类型
  • 跨域

解决思路

  • 浏览器 -> 加启动参数 --disable-web-security

  • XHR -> JSONP

  • 支持跨域

    • 被调用方解决(后台)
    • 调用方解决(转发平台)

什么是JSONP

content-type 
application/script

$.ajax({
...
dataType: "jsonp",
jsonp: "callback1", // 约定

修改后端 > 返回 函数

跨域

  • 简单请求 method GET HEAD POST Content-Type text/plain multpart/form-data application/x-www-form-urlencoded 无自定义头

  • 非简单请求 method put delete Content-Type application/json 自定义头

  • 被调用方

  * Access-Control-Allow-Origin *,(http://a.com)
  * Access-Control-Allow-Methods *
  * Access-Control-Allow-Headers 
  * Access-Control-Max-Age 3600 (s)

// enable cookie
withCredentials: true
Access-Control-Allow-Credentials: "true"
Access-Control-Allow-Origin 不能填'*'
  • 调用方
    • 转发设置
    b.com  
        proxy_pass http://localhost:8080/;
        
        add_header Access-Control-Allow-Methods *;
        add_header Access-Control-Max-Age 3600;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Headers $http_access_control_request_headers;
        add_header Access-Control-Allow-Origin $http_origin$;
        if ($requert_method = OPTIONS) {
            return 200; // 验证永远通过
        }
  • 反向代理
  a.com
        location /api {
          proxy_pass http://localhost/test/;
        }