我有一个Spring启动应用程序,我允许所有请求CORS过滤器。
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
从角度JS我打电话给这个服务器应用程序的一些休息api。 BUt我收到以下错误
Failed to load http://localhost:10230/place: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 400.
我这样的角度呼叫
function savePlace(place) {
return $http({
method: 'POST',
headers:{'X-TenantID': 'freight_management'},
data: place,
url: 'http://localhost:10230/place'
}).then(function (response) {
console.log(response.data);
return response.data;
}, function (reason) {
return reason;
});
}
我该如何解决?有什么遗失???
答案 0 :(得分:0)
虽然我今天使用代理解决了这个问题,但我常常像这样面对这个问题。
这允许每个来源。
这存储在CorsFilter.java
。
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type, X-XSRF-TOKEN");
response.addHeader("Access-Control-Expose-Headers", "xsrf-token, x-xsrf-token");
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
答案 1 :(得分:0)
您需要配置允许的来源:
registry.addMapping("/**").allowedOrigins("http://localhost:63342");