【发布时间】:2015-06-17 16:14:19
【问题描述】:
我有两个独立的服务器,一个是 nginx 和 node,另一个是 django 和 django-rest-framework 用于构建 REST API,nginx 负责 REST API 请求,node 负责客户端请求,我也使用polymer 作为前端。以下是简要说明:
一号机:
nginx:192.168.239.149:8888 (API listening address) forward to 192.168.239.147:8080
node:192.168.239.149:80 (client listening address)
机器二:
unicorn:192.168.239.147:8080(listening address)
流程是当请求进来时,节点服务器(192.168.239.149:80)响应返回html,在html中AJAX请求请求API服务器(@ 987654329@),然后unicorn(192.168.239.147:8080)返回结果。
但是有一个CORS的问题,我看了很多文章,很多人都遇到过同样的问题,我尝试了很多方法,但没有帮助。仍然错误。
我得到的是:
即:
XMLHttpRequest cannot load http://192.168.239.149:8888/article/. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers.
我要做的是:
<core-ajax auto headers='{"Access-Control-Allow-Origin":"*","X-Requested-With": "XMLHttpRequest"}' url="http://192.168.239.149:8888/article/" handleAs="json" response="{{response}}"></core-ajax>
nginx:
http {
include mime.types;
default_type application/octet-stream;
access_log /tmp/nginx.access.log;
sendfile on;
upstream realservers{
#server 192.168.239.140:8080;
#server 192.168.239.138:8000;
server 192.168.239.147:8080;
}
server {
listen 8888 default;
server_name example.com;
client_max_body_size 4G;
keepalive_timeout 5;
location / {
add_header Access-Control-Allow-Origin *;
try_files $uri $uri/index.html $uri.html @proxy_to_app;
}
location @proxy_to_app{
add_header Access-Control-Allow-Origin *;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
#proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
proxy_pass http://realservers;
}
}
}
节点:
app.listen(80, function() {
console.log('server.js running');
});
独角兽:
return Response(serializer.data,headers={'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'GET',
'Access-Control-Allow-Headers':'Access-Control-Allow-Origin, x-requested-with, content-type',
})
因为,我对CORS的经验不多,想彻底理解,谁能指出我在这里做错了什么,非常感谢!
【问题讨论】:
标签: django http cors polymer django-rest-framework