• 技术文章 >web前端 >js教程

    Angular客户端请求Rest服务跨域问题如何解决

    小云云小云云2018-02-05 15:30:18原创981
    本文主要和大家介绍Angular客户端请求Rest服务跨域问题的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。

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

    复制代码 代码如下:

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

    相关推荐:

    了解JavaScript,函数中的 Rest 参数

    以上就是Angular客户端请求Rest服务跨域问题如何解决的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:Angular Rest 客户端
    上一篇:jquery倒计时小应用实现代码 下一篇:jQuery实现IE6的遮罩功能
    PHP编程就业班

    相关文章推荐

    • 一文聊聊算法的时间复杂度和空间复杂度• 聊聊Angular 依赖注入体系中的基本概念• 什么是流?深入了解Node.js中的可读流• javascript技巧之拆箱装箱和类型转换• 看看这些jQuery常见面试题,帮助你更好理解基础知识!

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网