Tôi có một trang web với phân khúc sau:
api.example.com
developers.example.com
example.com
Tôi muốn cho phép cả hai example.comvà developers.example.comthực hiện các yêu cầu AJAX api.example.com.
Cấu hình nginx của tôi cho đến nay api.example.com, đó là một ứng dụng Rack đang được phục vụ bởi kỳ lân, trông như thế này:
upstream app_server {
server unix:/tmp/api.example.com.sock fail_timeout=0;
}
server {
listen 80;
server_name api.example.com;
access_log /home/nginx/api.example.com/log/access.log;
error_log /home/nginx/api.example.com/log/error.log;
location / {
add_header 'Access-Control-Allow-Origin' 'http://example.com,http://developers.example.com';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Content-Type,Accept';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app_server;
}
}
Dựa trên bài đọc của tôi, điều này là đủ cho những gì tôi đang cố gắng làm.
Các OPTIONS phản hồi:
HTTP/1.1 200 OK
Server: nginx/0.7.67
Date: Sat, 28 Apr 2012 17:20:08 GMT
Content-Type: application/json
Connection: close
Status: 200 OK
Content-Length: 0
Access-Control-Allow-Origin: http://developers.example.com,http://example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type,Accept
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Nhưng khi tôi thử các thao tác sau trong bảng điều khiển Chrome:
$.ajax("http://api.example.com", {
type: 'get',
contentType: "application/json",
accept: "application/json"
}).success(function(data){
console.log("success!", data);
}).fail(function(jqxhr, statusText){
console.log("fail!", jqxhr, statusText);
})
Tôi hiểu rồi:
XMLHttpRequest cannot load http://api.example.com/. Origin
http://developers.example.com is not allowed by Access-Control-Allow-Origin.
Và tương tự cho http://example.com .
Tôi đang thiếu gì?
Nếu tôi đặt Access-Control-Allow-Originđể *sau đó tôi thấy:
HTTP/1.1 200 OK
Server: nginx/0.7.67
Date: Sat, 28 Apr 2012 17:28:41 GMT
Content-Type: application/json
Connection: close
Status: 200 OK
Content-Length: 0
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type,Accept
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Nhưng yêu cầu jQuery vẫn thất bại, với chrome cũng nhấn mạnh rằng chuyến bay trước OPTIONSkhông thành công (mặc dù nó đã trả về 200 OK).
Access-Control-Allow-Headertiêu đề và sửa đổi cuộc gọi jQuery của mình như vậy:$.ajax("http://api.example.com", { type: 'get', crossDomain: true})Điều đó ngăn cản ánh sángOPTIONStrước xảy ra.