【发布时间】:2014-02-04 08:25:46
【问题描述】:
我正在尝试使用 POST 从 REST API 接收数据。我创建了应该发出 POST 请求的控制器。
function LoginCtrl($scope, $http, $rootScope) {
$scope.login = function () {
var form = {};
form.user = $scope.name;
form.pwd = $scope.password;
$http({
method: 'POST',
url: serverUrl+'/login',
data: $.param(form),
headers: {
'Content-type': 'application/json'
}
})
.success(function(data, status, headers, config) {
//success
})
.error(function(data, status, headers, config) {
//error
});
}
当我运行此代码时,浏览器会创建 OPTIONS 请求并显示 Access-Control-Allow-Origin(见下文)。我的 API 仅适用于 POST 请求,并且需要将 Content-type 标头设置为 application/json。
但是当我将 Content-type 更改为 application/x-www-form-urlencoded 浏览器发出 POST 请求时,我仍然看到错误:
XMLHttpRequest cannot load http://nimoz.asi.pl:8080/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
如何将 Content-type 标头设置为 application/json,保留 POST 方法并避免 Access-Control-Allow-Origin 错误?
我使用 AngularJS 版本 1.2.10。
编辑: 当我在 DEV HTTP CLIENT(Chrome 扩展)上测试 API 时,请求工作: http://scr.hu/277/hfwby
【问题讨论】:
标签: angularjs