angular中的$http请求跨域,采用CROS方式解决

it2022-06-28  70

anjular中的controller层$http服务,解决跨域请求。

js书写:

    /**     * 采用CORS方式实现ajax跨域请求     */    $http({        method:"post",  // 请求方式可以为post,也可以为get        params:"",        url:"http://localhost:8080/getArray",  // 跨域请求的路径    }).success(        function (response) {            $scope.array = response;        }    );

 

服务层书写:

    @RequestMapping("/getArray")    @ResponseBody    public List<Integer> getArray(HttpServletResponse response) {                List<Integer> list = new ArrayList<>();                list.add(1);        list.add(2);        list.add(3);        list.add(4);        list.add(4);        

  // 此处要添加需要跨域时,响应头,"http://localhost" 为 前端页面请求的源地址        response.setHeader("Access-Control-Allow-Origin", "http://localhost");                  return list;            }

 

添加的响应头信息,可以通过 浏览器页面查看相应的请求origin;同时也可以看出响应的时候,服务端的响应信息是否添加成功

 

转载于:https://www.cnblogs.com/rensheng/p/9998138.html

相关资源:数据结构—成绩单生成器

最新回复(0)