美文网首页
CORS and JSONP

CORS and JSONP

作者: JSL_FS | 来源:发表于2018-02-11 11:02 被阅读0次

    reference teacher run

    same-origin policy:

    1.protocol
    2.domain name
    3.port

    AJAX

    can only send message to same-origin site (diferent with JSONP、WebSocket、CORS)

    JSONP

    send request by script tag

    function addScriptTag(src) {
      var script = document.createElement('script');
      script.setAttribute("type","text/javascript");
      script.src = src;
      document.body.appendChild(script);
    }
    
    window.onload = function () {
      addScriptTag('http://example.com/ip?callback=foo');
    }
    
    function foo(data) {
      console.log('Your public IP address is: ' + data.ip);
    };
    

    WebSocket(a communication protocol )

    // config the request origin , from which domain
    //request head
    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13
    Origin: http://example.com  // key field
    
    //response head
    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
    Sec-WebSocket-Protocol: chat
    
    

    CORS ( Cross-origin resource sharing ): a W3C standard

    //front end 
    var xhr = new XMLHttpRequest()
    xhr.withCredentials = true
    
    GET /cors HTTP/1.1
    Origin: http://api.bob.com
    
    
    //server side
    Access-Control-Allow-Origin: http://api.bob.com
    Access-Control-Allow-Credentials: true
    
    

    JSONP can only suports GET method , it suport old explorers and sites don't surport CORS

    CORS suport all HTTP requests , it suports IE10+

    相关文章

      网友评论

          本文标题:CORS and JSONP

          本文链接:https://www.haomeiwen.com/subject/rsdktftx.html