Angular客户端请求Rest服务跨域问题的解决方法

1.问题描述:通过Origin是http://localhost:4200请求http://localhost:8081的服务,控制台报错如下,但是Response为200。客户端和服务端IP相同,但是端口不同,存在跨域问题。

代码如下:

2.解决方法:在服务端/api/v1/staffs的Restful方法增加@CrossOrigin注解,比如:

rush:js;"> @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",defaultValue = "0") int offset);

3.重新发送请求http://localhost:8081/api/v1/...,请求成功。且响应头增加了Access-Control-Allow-Credentials和Access-Control-Allow-Origin参数。@CrossOrigin注解即是给响应头增加了这两个参数解决跨域问题。

4.在服务端POST方法同样使用注解@CrossOrigin解决跨域问题。

rush:js;"> @CrossOrigin(origins = "*",method = RequestMethod.POST) RestResponse createStaff(@RequestBody RestRequest 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请求,请求成功。

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注解方式。推荐使用注解,方便。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...