vue前后端分离引发的跨域访问解决

    技术2022-07-10  97

    解决方式: 1.前端处理方式 在config目录下的index.js中添加proxyTable{}【本地开发常用方式】

    proxyTable: { '/sczjServer': { target: 'http://127.0.0.1:8082', changeOrigin: true, pathRewrite: { '^/sczjServer': '/sczjServer' } }, },

    2.后端处理方式 当然,不该前端的话,那就在后端添加拦截器,对请求进行跨域允许的设置

    @Component public class UrlInterceptor implements HandlerInterceptor { private static Logger logger = LoggerFactory.getLogger(UrlInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.addHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,PATCH"); response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");//Origin, X-Requested-With, Content-Type, Accept,Access-Token return true; } }

    或者直接在对应的controller添加支持跨域的注解,加入相关参数设置

    @CrossOrigin(allowCredentials = "true", allowedHeaders = "*")

    还有就是利用Nginx做代理,这里暂不做赘述。

    Processed: 0.009, SQL: 9