我一直在努力解决这个问题。
我使用了 yeoman generator angular-fullstack使用 Express 在 nodeJS 服务器上创建一个小的 Angular 应用程序。我正在使用远程服务,因此我的应用程序中没有编写任何 api 服务器端调用。
工厂:
var offerServiceURL = "https://www.example.com";
angular.module("services", ['ngResource'])
.factory('offerService', function($resource) {
return $resource(offerServiceURL+'/offers/service/:action/:param1',
{
action: '@action'
},
{
getOfferEligibility : {
method: 'POST',
params: {action:'get-offer-eligibility'}
}
});
});
Controller :
angular.module('myApp')
.controller('myCtrl', function($scope, offerService){
offerService.getOfferEligibility($scope.user, function(data){
if(data.status == "SUCCESS"){
....
}
})
})
Chrome 给我一个一般错误:
XMLHttpRequest cannot load https://example.com/offers/service/get-offer-eligibility. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost.digitalink.com:9000' is therefore not allowed access.
请求 header 使用正确的信息使其成为 OPTIONS:
Request Method:OPTIONS Status Code:200 OK Response Headers view source Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:content-type Access-Control-Allow-Methods:GET, POST, OPTIONS Access-Control-Allow-Origin:http://localhost.digitalink.com:9000
但是它在 POST 时中断并且没有正确的 header 。
事实上,我团队中的其他人能够使用在网页上运行的相同 Angular 工厂从他们的本地计算机成功访问该服务。我将我的 header 与成功 POST 上的 header 进行了比较。我的 POST 请求中缺少访问控制 header 。
我能想到的唯一差异是他们正在尝试使用端口 8080 的 Java 应用程序。这有什么不同吗?任何见解都会有所帮助!
最佳答案
您可以使用 expressjs 的 cors 模块在您的应用程序中启用 CORS。
安装
npm install cors
简单使用(启用所有 CORS 请求)
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
有关更多详细信息,请访问 https://github.com/expressjs/cors
关于javascript - Angular 全栈 + CORS : XMLHttpRequest cannot load,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29130853/