解决:Request header field Content-Type is not allowed by Access-Control-Allow-Headers

2022-04-13 16:16:51 浏览数 (1)

1. 前端 vue 工程 post 请求后端接口,报错:

代码语言:javascript复制
Request header field Content-Type is not allowed by Access-Control-Allow-Headers

前端请求方式:

代码语言:javascript复制
  this.$ajax({
        method: "post",
        url: this.GLOBAL.BASE_URL   "/gentle/first",
        data: {
          name: "JY",
          info: "test"
        }
      });

2. 解决:

在过滤器中设置请求头:

代码语言:javascript复制
resp.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE");

3. 过滤器完整写法:

过滤器用法见另一博文:Springboot 项目中过滤器的使用

代码语言:javascript复制
package gentle;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 改写所有请求头
 * @author silence
 * @date 2018/12/11 15:19
 */

@WebFilter(filterName = "requestFilter",urlPatterns = {"/*"})
public class RequestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest)servletRequest;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE,x-requested-with,Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String method = request.getMethod();
        if(method.equalsIgnoreCase("OPTIONS")){
            servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

}

4. 重新请求,访问接口成功 :

这样每次请求都会显示 2 次,第 1 次只返回个 success。第 2 次才是正式访问接口。

至于能不能只请求 1 次,目前我还不知道。

后记:

在网上看到可以在 js 中作如下设置,F12 中只提示一次请求。而且正好是我要的第 2 个请求,就是正式请求。

代码语言:javascript复制
let headers= new Headers();
headers.set('Content-Type','application/json');
headers.set('Access-Control-Allow-Origin','*');

0 人点赞