angularjs - 托管在 Pivotal Web 服务中的 Spring RESTful 没有 'Access-Control-Allow-Origin' 错误

标签 angularjs rest spring-boot cors cloud-foundry

我创建了一个 RESTful APISpring boot并将其托管在 Pivotal web services .

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

[

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

然后我编写了一个 Angular 客户端来向该 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 boot service我也允许 CORS , 也。
@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
}

但我不断收到此错误:
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 代码

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

   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() {}

}

我认为这可能有用

关于angularjs - 托管在 Pivotal Web 服务中的 Spring RESTful 没有 'Access-Control-Allow-Origin' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39565438/

相关文章:

rest - 支持资源嵌套

java - 尝试从 JSON 中嵌套的数组读取值

javascript - Angularjs UI 多选和初始选择

angularjs - 下拉菜单中的 Angular ui-sref 不起作用

rest - 合并两个包或尝试解决 Go 语言中的循环依赖

java - SpringBoot 2迁移ConfigurationProperties无法将属性绑定(bind)到String[]

java - Spring boot 和 maven exec 插件问题

postgresql - 测试容器和错误 : "Failed to validate connection org.postgresql.jdbc.PgConnection" (raising a single container for all test classes)

javascript - 尝试使用 ModalService。出现 "ModalService is undefined"错误

angularjs - 选项而不是 Post : Response to preflight request doesn't pass access control check.