如何做angular2:$ httpProvider.defaults.headers.common = {} [英] how to do in angular2: $httpProvider.defaults.headers.common = {}
问题描述
我有这个代码:
客户端(angular2)托管在这个网址上:
client (angular2) hosted on this url:
http://localhost:8080/Me/html/pages/gasolina/country/USA
代码:
return this.http
.post(this.supporToolSaveUrl, gasConfigModel, {headers: headers})
.map(res => res.json())
.subscribe(
data => {
console.info("next: ");
console.info(data)
},
err => console.error(err)
);
server(java jersey)
server (java jersey)
托管在这个网址上:
http://localhost:8080/Me/services/countries
代码:
@Path("/SaveConfig")
@POST
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public void saveConfig(CountryGasStationConfig countryGasStationConfig) throws Exception {
我应该在jersy注释中添加这些?
should i add these in jersy annotation?
当我在本地运行时出现此错误:
When i run locally i get this error:
MLHttpRequest cannot load http://locahost:8080/.... Response for preflight is invalid (redirect)
我看到了这个发布和这篇文章
I saw this post and this post
我怎样才能做到他在angular2中的解决方案?
How can i make this solution in angular2?
app。
config(['$httpProvider', function ($httpProvider) {
//Reset headers to avoid OPTIONS request (aka preflight)
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
}]);
推荐答案
您的java服务器已禁用CORS请求。在客户端更改请求将不起作用,因为在另一个URL上请求服务器时会自动创建OPTIONS请求(即使它只是localhost上的其他端口)。你无法解决这个问题。
Your java server has CORS requests disabled. Changing your requests on the client side will not work, because OPTIONS requests are automatically created when requesting a server on another URL (even if it's just a different port on localhost). There's no way you can get around this.
相反,你应该在java服务器上启用CORS。 这是java jersey的教程,它还详细介绍了CORS是什么。
Instead, you should enable CORS on your java server. Here's a tutorial for java jersey that also goes into details about what CORS is.
这篇关于如何做angular2:$ httpProvider.defaults.headers.common = {}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!