Javascript fetch 调用后端两次

问题描述

我有用 java ee 和 jersey 编写的后端应用程序。当我将数据发布到我的 rest 端点时,使用 JavaScript Fetch API 我看到过滤器被触发了两次。一旦它没有授权标头,第二个它有。当我尝试从网络浏览器打开我的网站时,这个过滤器只被调用一次。为什么会这样。也许是因为 CORS?

在我从同一个过滤器打印的单个帖子的日志下方。

 http://localhost:8080/BlogRest/controller/endpoint/|#]
  Key=host,value=localhost:8080|#]
  Key=origin,value=http://localhost:3000|#]
  Key=access-control-request-method,value=POST|#]
  Key=content-length,value=0|#]
  Key=access-control-request-headers,value=authorization,content-type|#]
  Key=connection,value=keep-alive|#]
  Key=accept,value=*/*|#]
  Key=user-agent,value=user agent data|#]
  Key=referer,value=http://localhost:3000/|#]
  Key=accept-language,value=pl-pl|#]
  Key=accept-encoding,value=gzip,deflate|#]
  

第二次通话

  http://localhost:8080/BlogRest/controller/endpoint/|#]
  Key=host,value=http://localhost:3000|#]
  Key=content-type,value=application/json|#]
  Key=accept-language,deflate|#]
  Key=connection,value=user agent data|#]
  Key=authorization,value=Bearer token|#]
  Key=referer,value=http://localhost:3000/origin|#]
  Key=content-length,value=15|#]

解决方法

因为 CORS 有两个请求。一种请求方法是 OPTIONS,当它被执行时,然后开始预期的 POST 请求。 OPTIONS 请求不调用端点,它只是获取服务器配置。所以我在我的 Java 过滤器请求中使用 HttpServletRequest getMethod() 进行过滤。

    @Override
    public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
            throws IOException,ServletException {

        HttpServletRequest requ = (HttpServletRequest) request;

        if (requ.getMethod().toLowerCase().equals(HttpMethod.OPTIONS)) {
            chain.doFilter(request,response);
            return;
        }

        //do something on not options method.            

        chain.doFilter(request,response);

    }