在Pivotal Web服务中托管的Spring RESTful没有“Access-Control-Allow-Origin”错误 [英] No 'Access-Control-Allow-Origin' error with Spring RESTful hosted in Pivotal web services

查看:649
本文介绍了在Pivotal Web服务中托管的Spring RESTful没有“Access-Control-Allow-Origin”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个 RESTful API Spring启动并托管在 Pivotal Web服务

I create a RESTful API with Spring boot and host it in Pivotal web services.

假设网址是 https://abc.cfapps.io/students ,json结果将为

Let's say the url is https://abc.cfapps.io/students and the json result will be

[

       {"id":1,"name":"Michael","score":8.5},
       {"id":2,"name":"Naomi","score":5.6}
]

然后我写一个Angular客户端发送请求到那个url:

Then I write an Angular client to send a request to that url:

angular.module("app", []).controller("listController", function($scope, $http)
{
    var url = 'https://abc.cfapps.io/students';
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', url, true);
    httpRequest.setRequestHeader('Access-Control-Allow-Origin', '*');
    httpRequest.setRequestHeader('Content-Type', 'application/json');
    httpRequest.onerror = function (XMLHttpRequest, textStatus, errorThrown) {
        console.log('failed');
        console.log(JSON.stringify(XMLHttpRequest));
    };
    httpRequest.onload = function () {
        console.log('SUCCESS!');
    }
    httpRequest.send();        
});

我的客户端在 localhost:52442 在我的 Spring启动服务中,我也允许 CORS

My client run in localhost:52442 and in my Spring boot service I also allow CORS, too.

@RestController
@CrossOrigin(origins = "http://localhost:52442")
@RequestMapping(value="/students")
public class StudentService
{

    @RequestMapping(value="/",method = RequestMethod.GET)
    public ArrayList<Student> getListStudents()
    {
        // return list
    }

// other methods
}

但我一直得到这个错误:

But I keep getting this error:

XMLHttpRequest cannot load https://abc.cfapps.io/students.         
Response to preflight request doesn't pass access control check:     
No 'Access-Control-Allow-Origin' header is present on the requested resource.        
Origin 'http://localhost:52442' is therefore not allowed access. The response had HTTP status code 403.


推荐答案

后端的java代码

我们可以尝试通过为它创建一个类来配置它

We can try to configure it in this way by creating a class for it

   package com.web;

   import org.springframework.stereotype.Component;

   import javax.servlet.*;
   import javax.servlet.http.HttpServletResponse;
   import java.io.IOException;

/**
 * Note this is a very simple CORS filter that is wide open.
 * This would need to be locked down.
 */
@Component
public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

我认为这可能有用

这篇关于在Pivotal Web服务中托管的Spring RESTful没有“Access-Control-Allow-Origin”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆