我正在 React 中开发一个前端应用程序,该应用程序连接到用 Spring Boot 编写的中间件服务。我正在尝试从前端调用端点,如下所示:
return axios.post('http://localhost:8085/workshop/client/createClient', {username})
.then((response) => {
console.log('Success')
})
.catch((error) => console.log(error));
每当我在浏览器中发出请求时,都会出现以下错误:
OPTIONS http://localhost:8085/workshop/client/createClient 401 ()
Failed to load http://localhost:8085/workshop/client/createClient: Response for preflight has invalid HTTP status code 401.
据我了解,这是因为我的中间件应用程序阻止了预检请求。在网上阅读了一些关于启用此功能的内容后,我在 Spring Boot 应用程序中添加了一个 CorsFilter:
@Slf4j
public class CORSFilter implements Filter {
private static final String ONE_HOUR = "3600";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
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, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", ONE_HOUR);
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type, Accept, x-device-user-agent, Content-Type");
if (req instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest) req;
if (httpServletRequest.getHeader(HttpHeaders.ORIGIN) != null
&& httpServletRequest.getMethod().equals(HttpMethod.OPTIONS.name())
&& httpServletRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD) != null) {
log.debug("Received an OPTIONS pre-flight request.");
return;
}
}
chain.doFilter(req, res);
}
@Override
public void destroy() {
}
}
和
@Configuration
public class MvcConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new CORSFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.setOrder(0);
return filterRegistrationBean;
}
}
这是端点的示例:
@PostMapping("/createClient")
public ResponseEntity<?> createClient(@RequestBody CreateClientDto clientDto) {
try {
...
return new ResponseEntity<>(responseBody, OK);
} catch (Exception e ...) {}
}
任何帮助将不胜感激 :)
更新:我的请求的 url 有点错误(因此是 404)。我已经更新了错误信息。我似乎仍然有 CORS 问题。
这些是我可以在开发工具中看到的响应标头:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:access-control-allow-credentials, access-control-allow-methods, access-control-allow-origin, allow, content-type
Access-Control-Allow-Methods:POST
Access-Control-Allow-Origin:http://localhost:3000
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:0
Date:Thu, 01 Mar 2018 14:06:38 GMT
Expires:0
Pragma:no-cache
Strict-Transport-Security:max-age=31536000 ; includeSubDomains
Vary:Origin
WWW-Authenticate:Basic realm="Spring"
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
和请求标头:
OPTIONS /workshop/client/createClient HTTP/1.1
Host: localhost:8085
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
Access-Control-Request-Headers: access-control-allow-credentials,access-control-allow-methods,access-control-allow-origin,allow,content-type
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,da;q=0.7