【发布时间】:2015-08-17 22:16:10
【问题描述】:
我正在使用 Angular JS 向 nodejs 服务器发送一些数据。
当我使用 curl 时,我会取回我发送的数据(正确结果):
curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" 'http://127.0.0.1:3000/s?table=register_rings&uid=1'
> {"MyKey":"My Value"}
但是,当我使用 angularjs 服务时,出现错误。
.factory('RegisterRingsService', function($http, $q) {
// send POST request with data and alert received
function send(data, uid) {
$http({
method: 'POST',
url: 'http://127.0.0.1:3000/s?table=register_rings&uid=1',
data: '{"MyKey":"My Value"}',
headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin":"*"},
responseType: 'json'
}).success(function(data, status, headers, config) {
alert('success', data, status);
}).error(function(data, status, headers, config) {
alert('error' + JSON.stringify(data) + JSON.stringify(status));
}).catch(function(error){
alert('catch' + JSON.stringify(error));
});
}
return {send : send};
})
错误如下:
{"data":null,"status":0,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://127.0.0.1:3000/s?table=register_rings","data":"{\"MyKey\":\"My Value\"}","headers":{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Accept":"application/json, text/plain, */*"},"responseType":"json"},"statusText":""}
我怀疑我应该插入 CORS 标头,但我不知道该怎么做。
任何帮助将不胜感激
【问题讨论】:
-
客户端不会像这样发送 CORS 头,服务器是发回
Access-Control-Allow-Origin: *让浏览器知道请求被允许的那个。