【发布时间】:2014-10-07 03:01:01
【问题描述】:
我有一个 node.js 服务器在我的计算机上本地运行。我正在使用 js-code 开发 html 页面:
var MainController = function($scope, $http) {
var onCountComplete = function(response) {
$scope.count = response.data;
};
var onError = function(reason) {
$scope.error = "Could not fetch data";
};
$http.get("http://localhost:1337/api/count")
.then(onCountComplete, onError);
$scope.message = "hello";
};
我在运行此代码时遇到错误:
XMLHttpRequest 无法加载
http://localhost:1337/api/count。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此,Origin 'file://' 不允许访问。
我尝试使用 --allow-file-access-from-files 键启动 Chrome,但没有帮助。有没有办法在开发过程中避免这个错误?
【问题讨论】:
-
您的 api 服务器上是否启用了 CORS?
-
你可以尝试在服务器端设置
Access-Control-Allow-Origin: *响应头吗? -
你在做跨域请求,这就是问题所在。您必须将服务器和客户端放在同一个域中或在服务器上启用 CORS
-
在 node.js 的情况下我该怎么做(在服务器上启用 CORS)?
-
如果您使用 Express,this link 可能会有所帮助。
标签: javascript angularjs