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

Posted

技术标签:

【中文标题】托管在 Pivotal Web 服务中的 Spring RESTful 没有“Access-Control-Allow-Origin”错误【英文标题】:No 'Access-Control-Allow-Origin' error with Spring RESTful hosted in Pivotal web services 【发布时间】:2017-01-26 16:29:02 【问题描述】:

我用Spring boot 创建了一个RESTful API 并将其托管在Pivotal web services 中。

假设 url 是 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.

【问题讨论】:

【参考方案1】:

如果你在后端使用 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() 


我认为这可能有用

【讨论】:

【参考方案2】:

尝试以下格式的$http GET 调用并设置标头以允许跨源

    $http(method: 'GET',
           url: 'https://abc.cfapps.io/students',
           cache:false,
           headers: 
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
                'X-Random-Shit':'123123123'
            )
            .success(function(outputData) 
    );

【讨论】:

以上是关于托管在 Pivotal Web 服务中的 Spring RESTful 没有“Access-Control-Allow-Origin”错误的主要内容,如果未能解决你的问题,请参考以下文章