# JSONP

# 原理

script标签可以从不同的域名加载资源,不受同源策略限制

原生实现方式:

script = document.createElement('script');
script.src = 'http://localhost:5000/jsonp?username=richard&callback=callback';
document.body.appendChild(script);
function callback(res) {
  console.log(res);
}
script.parentNode && script.parentNode.removeChild(script)

1
2
3
4
5
6
7
8

服务器端得配合jsonp的调用,返回一段Content-Type为application/javascript的脚本

app.get("/jsonp", (req, res) => {
  let {callback: callback = "callback", username} = req.query;
  res.type('application/javascript').send(`${callback}({username: "${username}", success: true})`);

});
1
2
3
4
5

# 缺点

  • 只能使用get方法

# CORS

跨域资源共享(Cross-origin resource sharing), 它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了Ajax只能同源使用的限制。

# 简单请求

同时满足下面的两条要求:

(1) 请求方法是HEAD/GET/POST

(2) HTTP的头不超出下面几种字段:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type: 只能是application/x-www-form-urlencoded、multipart/form-data、text/plain

对于简单请求,浏览器直接发出CORS请求,这个请求头会携带origin字段,表示这个请求的源。服务器回复根据这个字段,判断是否同意这次请求。如果不同意,就报错。如果同意,则响应头会有下面格式:

Access-Control-Allow-Origin: http://api.test.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8
1
2
3
4
  • Access-Control-Allow-Origin :该字段是必须的。它的值要么是请求时Origin字段的值,要么是一个*,表示接受任意域名的请求

  • Access-Control-Allow-Credentials: 该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。这个值也只能设为true,如果服务器不要浏览器发送Cookie,删除该字段即可。

  • Access-Control-Expose-Headers:该字段可选。CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。

浏览器发送携带cookie的CORS请求需满足:

  • 服务器同意,即响应头Access-Control-Allow-Credentials必须是true
  • 服务器Access-Control-Allow-Origin就不能设为星号,必须指定明确的、与请求网页一致的域名
  • 浏览器在ajax请求中打开withCredentials
// 原生
var xhr = new XMLHttpRequest(); 
xhr.withCredentials = true; // 主动打开withCredentials
xhr.open('post', 'http://api.test.com/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
};
// jquery
$.ajax({
  ...
  xhrFields: {
    withCredentials: true // 前端设置是否带cookie
  },
  crossDomain: true, // 会让请求头中包含跨域的额外信息,但不会含cookie
  ...
});

// axios
axios.post(
  'http://api.test.com/login', 
  {
    username: "richard",
    password: "test"
  },
  {
    // 单独配置
    withCredentials: true
  })
  .then(function(res) {
    console.log(res.data);
  })
  .catch(function(err) {
    console.error(err);
  });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

# 非简单请求

比如请求方法是PUT或DELETE,或者Content-Type字段的类型是application/json。非简单请求的CORS请求,会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求(preflight),请求方法为options

options请求头

OPTIONS /cors HTTP/1.1
Origin: http://b.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: b.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
1
2
3
4
5
6
7
8

浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些HTTP动词和头信息字段。只有得到肯定答复,浏览器才会发出正式的XMLHttpRequest请求,否则就报错。

服务器响应头与CORS相关的如下:

Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 1728000
1
2
3
4
  • Access-Control-Allow-Methods:该字段必需,它的值是逗号分隔的一个字符串,表明服务器支持的所有跨域请求的方法。注意,返回的是所有支持的方法,而不单是浏览器请求的那个方法。这是为了避免多次"预检"请求。

  • Access-Control-Allow-Headers:如果浏览器请求包括Access-Control-Request-Headers字段,则Access-Control-Allow-Headers字段是必需的。它也是一个逗号分隔的字符串,表明服务器支持的所有头信息字段,不限于浏览器在"预检"中请求的字段。

  • Access-Control-Allow-Credentials: 该字段与简单请求时的含义相同。

  • Access-Control-Max-Age: 该字段可选,用来指定本次预检请求的有效期,单位为秒。上面结果中,有效期是20天(1728000秒),即允许缓存该条回应1728000秒(即20天),在此期间,不用发出另一条预检请求。

# postMessage跨域

H5提出来的API,IE8+, chrome, ff都已经支持。

例子:

http://www.a.com/a.html

<iframe id="iframe" src="http://www.b.com/b.html" style="display:none;"></iframe>
<script>
    var iframe = document.getElementById('iframe');
    iframe.onload = function() {
      var data = {
          name: 'aaaaa'
      };
      // 向b传送跨域数据
      iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.b.com');
    };
    // 接受b返回数据
    window.addEventListener('message', function(e) {
      console.log(e);
      // 安全拦截
      if(e.origin !== "http://www.b.com") return;
    }, false);

</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

http://www.b.com/b.html

<script>
// 接收a的数据
window.addEventListener('message', function(e) {
    console.log(e);
    // 安全拦截
    if(e.origin !== "http://www.a.com") return;
    var data = JSON.parse(e.data);
    if (data) {
        data.name = "bb";
        // 处理后再发回a.com
        window.parent.postMessage(JSON.stringify(data), 'http://www.a.com');
    }
}, false);

</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
上次更新: 2020-03-03 11:42:44