解决Request header field XXX is not allowed by access-control-allow-headers in preflight response

问题

Access to XMLHttpRequest at ‘http://B.com/path/a’ from origin ‘http://A.com’ has been blocked by CORS policy: Request header field AC-User-Agent is not allowed by Access-Control-Allow-Headers in preflight response.

在这里插入图片描述




产生原因

前后端分离项目,由于老版本项目没有接入网关和微服务,因此需要通过域名加接口地址的方式来直接访问,因此出现以下情况:

网站主域名是A.com,老接口服务的域名是B.com。
在调用老接口服务时,要求前端在header里必须加上AC-User-Agent字段,用于实现老接口业务
在这种情况下,前端在A.com网站上调用B.com,由此产生上述问题




解决方法

由于是跨域调用B.com接口时,未允许使用请求头AC-User-Agent(Request header field AC-User-Agent is not allowed by Access-Control-Allow-Headers),因此需要在B.com的Java代码里面新建一个过滤器,在过滤器中设置AC-User-Agent为合法请求头

@WebFilter("/*")
public class CorsFilter implements Filter {

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

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

		HttpServletResponse resp = (HttpServletResponse) servletResponse;
		HttpServletRequest req = (HttpServletRequest) servletRequest;

		String origin = req.getHeader("Origin");
		resp.setHeader("Access-Control-Allow-Origin", origin);
		resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
		resp.setHeader("Access-Control-Allow-Headers", "AC-User-Agent, token, content-type");
		resp.setHeader("Access-Control-Allow-Credentials", "true");
		filterChain.doFilter(servletRequest, servletResponse);
	}

	@Override
	public void destroy() {
	}
}

你可能感兴趣的:(java,java,开发语言)