Angular客户端请求Rest服务跨域问题的解决方法
1.问题描述:通过origin是http://localhost:4200请求http://localhost:8081的服务,控制台报错如下,但是response为200。客户端和服务端ip相同,但是端口不同,存在跨域问题。
xmlhttprequest cannot load http://localhost:8081/api/v1/staffs. no 'access-control-allow-origin' header is present on the requested resource. origin 'http://localhost:4200' is therefore not allowed access.
2.解决方法:在服务端/api/v1/staffs的restful方法增加@crossorigin注解,比如:
@crossorigin(origins = "*", maxage = 3600) @requestmapping(value = "/api/v1/staffs", produces = { "application/json" }, method = requestmethod.get) restresponselist<?> querystaffs(@requestparam(value = "limit", required = false, defaultvalue = "20") int limit, @requestparam(value = "offset", required = false, defaultvalue = "0") int offset);
3.重新发送请求http://localhost:8081/api/v1/...,请求成功。且响应头增加了access-control-allow-credentials和access-control-allow-origin参数。@crossorigin注解即是给响应头增加了这两个参数解决跨域问题。
4.在服务端post方法同样使用注解@crossorigin解决跨域问题。
@crossorigin(origins = "*", maxage = 3600) @requestmapping(value = "/api/v1/staffs", produces = { "application/json" }, method = requestmethod.post) restresponse<?> createstaff(@requestbody restrequest<staffreqinfo> request);
报错如下:
5.查看响应码415,错误原因:
"status": 415,
"error": "unsupported media type",
"exception": "org.springframework.web.httpmediatypenotsupportedexception",
"message": "content type 'text/plain;charset=utf-8' not supported"
6.进一步查看请求头信息,content-type为text/plain。与response headers的content-type:application/json;charset=utf-8类型不匹配,故报错。
7.指定请求头content-type为application/json,比如在angular中增加headers。发送post请求,请求成功。
let headers = new headers({ 'content-type': 'application/json' }); let options = new requestoptions({ headers }); return this.http.post(this.staffcreateurl, body, options).map((response: response) => { //return this.http.get(this.userloginurl).map((response:response)=> { let responseinfo = response.json(); console.log("====请求staffcreateurl成功并返回数据start==="); console.log(responseinfo); console.log("====请求staffcreateurl成功并返回数据end==="); let staffname = responseinfo.responseinfo.staffname; console.log(staffname); return responseinfo; })
另:也可以在httpservletresponse对象通过setheader("access-control-allow-origin", "*")方法增加响应头参数,解决跨域问题,即是@crossorigin注解方式。推荐使用注解,方便。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: AngularJS实现注册表单验证功能
下一篇: Angular弹出模态框的两种方式