Nginx CORS實現JS跨域

1. 什麼是跨域

簡單地理解就是由於JavaScript同源策略的限制,a.com 域名下的js沒法操做b.com或是c.a.com域名下的對象。javascript

同源是指相同的協議、域名、端口。特別注意兩點:css

  • 若是是協議和端口形成的跨域問題「前臺」是無能爲力的,
  • 在跨域問題上,域僅僅是經過「協議+域名+端口」來識別,兩個不一樣的域名即使指向同一個ip地址,也是跨域的。

2. 跨域解決方案

跨域解決方案有多種,大可能是利用JS Hack:html

3. CORS

CORS: 跨域資源共享(Cross-Origin Resource Sharing)http://www.w3.org/TR/cors/java

當前幾乎全部的瀏覽器(Internet Explorer 8+, Firefox 3.5+, Safari 4+和 Chrome 3+)均可經過名爲跨域資源共享(Cross-Origin Resource Sharing)的協議支持ajax跨域調用。(see: http://caniuse.com/#search=cors)nginx

Chrome, Firefox, Opera and Safari 都使用的是 XMLHttpRequest2 對象, IE使用XDomainRequest。XMLHttpRequest2的Request屬性:open()、setRequestHeader()、timeout、withCredentials、upload、send()、send()、abort()。git

XMLHttpRequest2的Response屬性:status、statusText、getResponseHeader()、getAllResponseHeaders()、entity、overrideMimeType()、responseType、response、responseText、responseXML。github

啓用 CORS 請求

假設您的應用已經在 example.com 上了,而您想要從 www.example2.com 提取數據。通常狀況下,若是您嘗試進行這種類型的 AJAX 調用,請求將會失敗,而瀏覽器將會出現「源不匹配」的錯誤。利用 CORS,www.example2.com 服務端只需添加一個HTTP Response頭,就能夠容許來自 example.com 的請求:ajax

Access-Control-Allow-Origin: http://example.com
Access-Control-Allow-Credentials: true(可選)

可將 Access-Control-Allow-Origin 添加到某網站下或整個域中的單個資源。要容許任何域向您提交請求,請設置以下:json

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true(可選)

其實,該網站 (html5rocks.com) 已在其全部網頁上均啓用了 CORS。啓用開發人員工具後,您就會在咱們的響應中看到 Access-Control-Allow-Origin 了。

提交跨域請求

若是服務器端已啓用了 CORS,那麼提交跨域請求就和普通的 XMLHttpRequest 請求沒什麼區別。例如,如今 example.com 能夠向 www.example2.com 提交請求了:

var xhr = new XMLHttpRequest();
// xhr.withCredentials = true; //若是須要Cookie等
xhr.open('GET', 'http://www.example2.com/hello.json');
xhr.onload = function(e) {
  var data = JSON.parse(this.response);
  ...
}
xhr.send();

4. 服務端Nginx配置

要實現CORS跨域,服務端須要這個一個流程:http://www.html5rocks.com/static/images/cors_server_flowchart.png

對於簡單請求,如GET,只須要在HTTP Response後添加Access-Control-Allow-Origin。

對於非簡單請求,好比POST、PUT、DELETE等,瀏覽器會分兩次應答。第一次preflight(method: OPTIONS),主要驗證來源是否合法,並返回容許的Header等。第二次纔是真正的HTTP應答。因此服務器必須處理OPTIONS應答。

http://enable-cors.org/server_nginx.html這裏是一個nginx啓用COSR的參考配置。

流程以下:

  1. 首先查看http頭部有無origin字段;
  2. 若是沒有,或者不容許,直接當成普通請求處理,結束;
  3. 若是有而且是容許的,那麼再看是不是preflight(method=OPTIONS);
  4. 若是是preflight,就返回Allow-Headers、Allow-Methods等,內容爲空;
  5. 若是不是preflight,就返回Allow-Origin、Allow-Credentials等,並返回正常內容。

用僞代碼表示:

location /pub/(.+) {
    if ($http_origin ~ <容許的域(正則匹配)>) {
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Credentials' "true";
        if ($request_method = "OPTIONS") {
            add_header 'Access-Control-Max-Age' 86400;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE';
            add_header 'Access-Control-Allow-Headers' 'reqid, nid, host, x-real-ip, x-forwarded-ip, event-type, event-id, accept, content-type';
            add_header 'Content-Length' 0;
            add_header 'Content-Type' 'text/plain, charset=utf-8';
            return 204;
        }
    }
    # 正常nginx配置
    ......
}

可是因爲Nginx 的 if 是邪惡的,因此配置就至關地讓人不爽(是個人配置不夠簡潔嗎?)。下面nginx-spdy-push裏/pub接口啓用CORS的配置:

# push publish
# broadcast channel name must start with '_'
# (i.e., normal channel must not start with '_')

# GET /pub/channel_id -> get statistics about a channel
# POST /pub/channel_id -> publish a message to the channel
# DELETE /pub_admin?id=channel_id -> delete the channel

#rewrite_log on;

# server_name test.gw.com.cn
# listen 2443 ssl spdy

location ~ ^/pub/([-_.A-Za-z0-9]+)$ {

    set $cors "local";

    # configure CORS based on https://gist.github.com/alexjs/4165271
    # (See: http://www.w3.org/TR/2013/CR-cors-20130129/#access-control-allow-origin-response-header )

    if ( $http_origin ~* "https://.+\.gw\.com\.cn(?=:[0-9]+)?" ) {
        set $cors "allow";
    }
    if ($request_method = "OPTIONS") {
        set $cors "${cors}options";
    }

    # if CORS request is not a simple method
    if ($cors = "allowoptions") {
        # Tells the browser this origin may make cross-origin requests
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        # in a preflight response, tells browser the subsequent actual request can include user credentials (e.g., cookies)
        add_header 'Access-Control-Allow-Credentials' "true";

        # === Return special preflight info ===

        # Tell browser to cache this pre-flight info for 1 day
        add_header 'Access-Control-Max-Age' 86400;

        # Tell browser we respond to GET,POST,OPTIONS in normal CORS requests.
        # Not officially needed but still included to help non-conforming browsers.
        # OPTIONS should not be needed here, since the field is used
        # to indicate methods allowed for 'actual request' not the preflight request.
        # GET,POST also should not be needed, since the 'simple methods' GET,POST,HEAD are included by default.
        # We should only need this header for non-simple requests methods (e.g., DELETE), or custom request methods (e.g., XMODIFY)
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE';

        # Tell browser we accept these headers in the actual request
        add_header 'Access-Control-Allow-Headers' 'reqid, nid, host, x-real-ip, x-forwarded-ip, event-type, event-id, accept, content-type';

        # === response for OPTIONS method ===

        # no body in this response
        add_header 'Content-Length' 0;
        # (should not be necessary, but included for non-conforming browsers)
        add_header 'Content-Type' 'text/plain, charset=utf-8';
        # indicate successful return with no content
        return 204;
    }

    if ($cors = "allow") {
        rewrite /pub/(.*) /pub_cors/$1 last;
    }

    if ($cors = "local") {
        rewrite /pub/(.*) /pub_int/$1 last;
    }
}

location ~ /pub_cors/(.*) {
    internal;
    # Tells the browser this origin may make cross-origin requests
    add_header 'Access-Control-Allow-Origin' "$http_origin";
    # in a preflight response, tells browser the subsequent actual request can include user credentials (e.g., cookies)
    add_header 'Access-Control-Allow-Credentials' "true";

    push_stream_publisher                   admin; # enable delete channel
    set $push_stream_channel_id             $1;

    push_stream_store_messages              on;  # enable /sub/ch.b3
    push_stream_channel_info_on_publish     on;
}

location ~ /pub_int/(.*) {
  # internal;
    push_stream_publisher                   admin; # enable delete channel
    set $push_stream_channel_id             $1;

    push_stream_store_messages              on;  # enable /sub/ch.b3
    push_stream_channel_info_on_publish     on;
}

5. 客戶端javascript代碼

下面是https://spdy.gw.com.cn/sse.html裏的代碼

var xhr = new XMLHttpRequest();
//xhr.withCredentials = true;
xhr.open("POST", "https://test.gw.com.cn:2443/pub/ch1", true);
// xhr.setRequestHeader("accept", "application/json");

xhr.onload = function()  {
  $('back').innerHTML = xhr.responseText;
  $('ch1').value = + $('ch1').value + 1;
}
xhr.onerror = function() {
  alert('Woops, there was an error making the request.');
};

xhr.send($('ch1').value);

頁面的域是https://spdy.gw.com.cn, XMLHttpRequest的域是https://test.gw.com.cn:2443,不一樣的域,而且Post方式。

用Chrome測試,能夠發現有一次OPTIONS應答。如過沒有OPTIONS應答,多是以前已經應答過,被瀏覽器緩存了'Access-Control-Max-Age' 86400;,清除緩存,再試驗。

6. 相關連接

相關文章
相關標籤/搜索