将本地 React 前端连接到本地 Spring Boot 中间件应用程序时出现 CORS 错误

IT技术 java reactjs rest spring-boot cors
2021-05-14 23:27:56

我正在 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
4个回答

我也有这个问题,但请允许我以更简单的沟通方式给出直接的答案。

首先,您必须告诉您的服务器(Spring boot java)有关客户端(Reactjs)URL 的信息

例如,大多数时候 spring boot 使用http://localhost:8080和 Reactjs uses http://localhost:3000

因此,您必须导航到 Spring boot java 中的控制器,并允许ReactjsURL获得服务器中可访问性的权限(Spring boot)。这将帮助您摆脱CORS问题。

我们如何在 Spring Boot 中做到这一点?只需添加@CrossOrigin指定 Reactjs URL链接注释,如下所示:

例如 :

    @GetMapping("/orphans")
    @CrossOrigin(origins = "http://localhost:3000")
    Iterable<Student> read() {
        return studentService.findAll();
    }

上面的方法是列出所有孤儿,所以我给了 Reactjs URL链接权限,然后我摆脱了CORS问题。

快乐编码。

控制器.java

请参阅以下示例代码来解决此问题。

@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value="/sample", method = RequestMethod.GET, produces = "application/json")

public Student getStudent(){
}

这是一个标准的 CORS 问题,这基本上意味着用户代理 iehttp://localhost:3000没有访问资源的权限http://localhost:8085您可以在https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS了解更多相关信息

您的请求标头应该完全映射到服务器规则。保留任何参数*都行不通。

例如,如果您的请求标头具有以下内容:

Access-Control-Request-Method: POST
Access-Control-Request-Headers: <your custom headers>

然后,服务器规则显示映射您的请求标头:

Access-Control-Request-Method: GET, PUT, DELETE, POST
Access-Control-Request-Headers: <your custom headers>

如果有帮助,请告诉我!

问题似乎得到了解决。我错过了 Accept 请求标头(感谢@Anadi Sharma),而且我还将 spring-boot-starter-security 作为依赖项,它似乎未经授权返回。我也不需要 CorsFilter,最后我只是在端点上使用了 @CrossOrigin 注释。