我正在尝试在angularJS应用中使用$ http服务,但我在控制台中收到以下错误。
XMLHttpRequest cannot load http://example.com/data.service/getSomething/hghfg7igb757. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://other-example.dev' is therefore not allowed access.
这是我的AngularJS控制器:
app.controller('mainController', ['$scope', '$http', function($scope, $http){
var url = 'http://example.com/data.service/getSomething/hghfg7igb757';
$http({
method: 'GET',
cache: true,
url: url,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).
success(function(status) {
//your code when success
$scope.data = data;
}).
error(function(status) {
//your code when fails
});
}]);
我读过这可能与我的服务器配置有关,我正在使用gulp-connect https://www.npmjs.com/package/gulp-connect。或者它是否与我要求的网站的服务器配置有关?
我用curl检查了http标题,但它似乎没有告诉我多少?
$ curl -I http://example.com/data.service/getSomething/hghfg7igb757
HTTP/1.1 200 OK
Date: Wed, 07 Dec 2016 22:35:19 GMT
Server: WildFly/8
Expires: Wed, 07 Dec 2016 22:40:19 GMT
X-Powered-By: Undertow/1
X-dmg-elapsed-time: 30ms
X-dmg-host-address: 17?.??.???.?0
X-dmg-generated-time: Wed, 07 Dec 2016 22:35:19 GMT
Content-Type: application/json;charset=UTF-8
Content-Language: en-
X-dmg-node-name: dbfr_node_1
Vary: Accept-Encoding
X-Varnish-Bereq-Backend: real_backend_llr
X-Varnish-Bereq-Retries: 0
Last-Modified: Wed, 07 Dec 2016 22:35:19 GMT
Cache-Control: public, max-age=300
X-Varnish: 1376270
Age: 0
Via: 1.1 varnish-v4
X-Varnish-Cache: MISS
X-Varnish-Served-By-Host: jul.max.ie
X-Varnish-Served-By-IP: 1?.???.??.??
X-Varnish-Pool: http_pages
X-Varnish-Req-Backend-Hint: dead
X-Varnish-Req-Restarts: 0
X-Varnish-Hash: /data.service/getSomething/hghfg7igb757
X-Varnish-Backend-Ourself: varnish_server_jul_llr
X-DMG-Version: 6.20.51.2358
Accept-Ranges: none
Connection: keep-alive
答案 0 :(得分:1)
安装cors包: npm install --save-dev cors
然后将其添加为连接中间件:
var gulp = require('gulp');
var connect = require('gulp-connect');
var cors = require('cors');
gulp.task('connect', function() {
connect.server({
root: 'app',
middleware: function() {
return [cors()];
}
});
});
- https://github.com/AveVlad/gulp-connect/issues/100#issuecomment-74369427
如何查看回复中的标题?
$http(...).
then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
console.log(headers());
}).
catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
console.log(headers());
});
$ http已弃用的自定义回调方法 - success()
和error()
- 已被删除。您可以使用标准then()
/ catch()
promise方法,但请注意方法签名和返回值不同。
- AngularJS Developer Guide - Migrating from 1.5 to 1.6 - $http
答案 1 :(得分:0)
这在服务器端是一个CORs问题