【发布时间】:2016-07-15 08:58:59
【问题描述】:
我的 Java Spring API 启用了 CORS,我想使用 AngularJS 对其进行调用。我首先编写了一个演示 jQuery 代码来测试 CORS,它运行良好。然后我写了一个等效的 AngularJS 代码,它总是产生相同的错误 -
XMLHttpRequest cannot load http://localhost:8080/my_project_name/api/get_some_data. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 401.
在研究从 AngularJS 发出 CORS 请求时,大多数结果都表明 AngularJS 在发出 CORS 请求时不需要进行任何更改,但它似乎不起作用。有什么我做错或遗漏的吗?顺便说一句,我正在使用 AngularJS v1.3.15。
以下是我在 Spring 应用程序中启用 CORS 的方式 (BaseWebConfig 扩展 WebMvcConfigurerAdapter) -
public class WebConfig extends BaseWebConfig {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
ResourceHttpMessageConverter resourceHttpMessageConverter = new ResourceHttpMessageConverter();
converters.add(resourceHttpMessageConverter);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// allow cross-origin API requests
registry
.addMapping("/api/**")
.allowedMethods(
HttpMethod.GET.name(),
HttpMethod.HEAD.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.OPTIONS.name())
.allowCredentials(false);
}
}
我首先使用如下的 jQuery 代码测试 CORS,它运行良好 -
$(function() {
$('#submit_jquery').click(function() {
var token = $('#token').val().trim();
var headerValue = "Bearer " + token;
var body = $('#body').val().trim();
var domain = $('#api_domain').val().trim();
$('#result').text('');
$.ajax({
method : 'POST',
url : domain + '/api/get_some_data',
contentType : 'application/json',
data : body,
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", headerValue);
},
success : function(json) {
console.log('success');
$('#result').html('<pre>' + JSON.stringify(json, undefined, 2) + '</pre>');
},
error : function(xhr, textStatus, errorThrown) {
console.log('error');
},
complete : function() {
console.log('complete');
}
});
return false;
});
});
然后我写了一个等效的AngularJS代码如下-
app.controller('CorsController', ['$scope', '$http',
function($scope, $http) {
$scope.makeCorsRequest = function() {
var token = $('#token').val().trim();
var headerValue = "Bearer " + token;
var body = $('#body').val().trim();
var domain = $('#api_domain').val().trim();
var url = domain + '/api/get_some_data';
var header = {'Authorization': headerValue, 'Content-Type': 'application/json'};
$http({
method: 'POST',
url: url,
header: header,
data: body
}).then(
//success callback
function (data) {
console.log('SUCCESS');
console.log(data);
},
//error callback
function (errorMessage) {
console.error('ERROR');
console.error(errorMessage);
}
);
};
}]);
从 jQuery 调用时的 API 响应头如下。浏览器实际上进行了两次调用-
第一个响应的标题 -
Access-Control-Allow-Headers:accept, authorization, content-type
Access-Control-Allow-Methods:GET,HEAD,POST,PUT,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1800
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length:0
Date:Mon, 28 Mar 2016 10:30:00 GMT
Server:Apache-Coyote/1.1
Vary:Origin
第二个响应的标题 -
Access-Control-Allow-Origin:*
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json
Date:Mon, 28 Mar 2016 10:30:00 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
【问题讨论】:
标签: jquery angularjs ajax spring cors