首先需要明确跨域的含义。
- 域名不同,跨域!
- 端口不同,跨域!
其次,如果出现跨域的情况,解决方案有两种,分为前端,后端两种均需要修改配置:
1.前端
修改vue项目config下的index.js,招到proxyTable
添加一下代码:
'/api': { //替换代理地址名称
target: 'http://api.douban.com/', //代理地址
changeOrigin: true, //可否跨域
pathRewrite: {
'^/api': '' //重写接口,去掉/api
}
}
2.后端
配值全局过滤器,允许全部/个别ip,端口,请求方式访问
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CorsFilter implements Filter {
final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
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");
System.out.println("*********************************过滤器被使用**************************");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}