我有一个带有hapiJS API的节点服务器,我正在尝试从单独的节点服务器发送请求 .
一切都在开发中工作正常,但在服务器上却没有,问题是服务器上启用了基本身份验证 .
具体来说,如果请求是GET请求,则请求正常,但所有其他请求都失败 . 我怀疑这是由于OPTIONS预请求航班检查失败,而我的有限理解不会发送GET请求 .
我得到的确切错误消息是:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://site.example.com' is therefore not allowed access. The response had HTTP status code 401.
我的nginx配置:
server {
listen 80;
server_name https://api.example.com;
return 301 https://$server_name$request_uri; ## Permanently redirect all http traffic to https
}
server {
#SSL INIT
listen 443;
ssl on;
ssl_certificate /var/vcap/jobs/nginx/config/site.bundle.crt;
ssl_certificate_key /var/vcap/jobs/nginx/config/site.key;
server_name https://api.example.com;
location / {
auth_basic "Restricted Content";
auth_basic_user_file .htpasswd;
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-NginX-Proxy true;
proxy_pass_request_headers on;
proxy_pass https://api.example.com;
}
}
我的HAPiJS的CORS设置(我排除了无关的东西) .
connections:
routes:
cors:
origin: ["https://api.example.com"]
credentials: true
我已经尝试了https://www.npmjs.com/package/hapi-cors-headers hapi-cors-headers插件,但没有用(而不是上面的设置 . )我尝试在nginx上启用我能想到的每一个CORS事物(大部分来自http://enable-cors.org/server_nginx.html)
无论我如何调整配置,都会发生以下两种情况之一 - 我尝试过很多事情:1)无论如何,它都会继续发出上述信息2)它抱怨 Headers 在那里TWICE(如果我同时把它放在nginx和hapijs中) .
在任何情况下它都不起作用(GET请求除外) .
POST ajax调用我正在使用的API(与Kendo一起使用)的示例:
$.ajax({
url: api_address + '/vendors',
method: 'POST',
contentType: 'application/json',
processData: false,
data: JSON.stringify(this.vendor),
xhrFields: {
withCredentials: true
}
success: function(data) {
vm.set('vendor', data);
notification.show('Vendor created successfully', 'success');
vm.set('has_changes', false);
},
error: function() {
notification.show('Error creating vendor', 'error');
}
});
上面提到的api_address是:
https://username:password@api.example.com
为什么这适用于GET请求但不适用于POST / PUT / etc?
1 回答
更改你的nginx来处理CORS并且没有hapi担心它 . 采取和修改http://enable-cors.org/server_nginx.html
当然,如果您支持PUT或DELETE,则需要更多工作 .