gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:17:40 24 4
gpt4 key购买 nike

我创建了一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com