跨域问题
报错信息为:Failed to load http://localhost:8080/jfly.openapi/produce/listMachFeedingBoard/v1: Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
原因:前台发送的请求体包含了没有允许的Header
如何解决问题:在后台过滤器中加入允许的Header类型
原有代码: response.setHeader(“Access-Control-Allow-Headers”, “x-requested-with,Authorization”);
修改后: response.setHeader(“Access-Control-Allow-Headers”, "x-requested-with,Authorization,Content-Type");
在这里设置允许的Header的类型,加入Content-Type后问题解决
package com.jfly.apps.restful.springmvc;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class CORSInterceptor 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;
String origin = (String) servletRequest.getRemoteHost() + ":" + servletRequest.getRemotePort();
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", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}