当使用js访问WebService时会出现跨域问题;
解决办法:
服务端添加
Access-Control-Allow-Origin: *;
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE;
Access-Control-Max-Age:3600;
Access-Control-Allow-Headers:x-requested-with,Authorization;
Access-Control-Allow-Credentials:true;
新建一个拦截器:
import java.io.IOException; import javax.servlet.*; import javax.servlet.ServletRequest; import javax.servlet.annotation.WebFilter; import javax.servlet.http.*; import javax.xml.ws.WebFault; import org.springframework.stereotype.Component; @Component public class CustomerCORSFilter 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(); System.out.println(origin); 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() { } }
每次请求都会在head加上即可解决跨域问题