前端Vue访问SpringBoot后台,如何从后台解决跨域问题

如题

从后台解决,大多都是

/**
 * 跨域请求支持
 */
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport{

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*");
    }

    @Override
    protected void configureAsyncSupport(AsyncSupportConfigurer configurer){
        configurer.setTaskExecutor(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(3)));
        configurer.setDefaultTimeout(30000);
        }
}

然而发现还是无效

clipboard.png

原则上,我想从后台解决,当然,如果前端有比后端好的解决方法也可以从前端解决,希望大佬帮忙

阅读 7.8k
4 个回答

非常抱歉,后来发现是前端axios请求造成的问题,并不是真正意义上的跨域问题,我照着网上axios发送请求的方式,结果后来发现那篇文章的axios请求有问题,无法正确发送请求,所以从后端处理的跨域问题,是有效的

nginx 或者 如果用 webpack 的话 可以配下 proxy, 代理一下。

实现一个filter即可。

@Component
public class SimpleCORSFilter implements Filter {

    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");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {

    }

    public void destroy() {

    }

}

参考:https://www.jianshu.com/p/daf...

使用 webpack 提供devServer选项来配置代理即可
先来举例,比如现在
前端工程访问为: http://127.0.0.1:8080
后端地址为: http://127.0.0.1:3000

假如现在后端有一个查找用户 user 的接口, 地址为 http://127.0.0.1:3000/user
由于端口不一样,这样就会出现跨域问题,那么怎么来解决这个问题;

假如前端请求方式如下:

  axios.post('/api/user')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

当发送 post 请求时,完整的请求地址为: http://127.0.0.1:8080/api/user , 先说说为什么需要添加一个 api 前缀, 这里因为需要我们区别哪些接口需要代理,并不是所有的请求都需要拦截; 如 css,js,image

webpack 配置代码如下:

module.exports = {
  devServer: {
    proxy: { 
      '/api': 'http://127.0.0.1:3000',
      // 重写 path 
      pathRewrite: {    
          '^/api': ''   // 把 '/api/user' 替换为 '/user'
      }
    }
  }
};

注意:pathRewrite 这里作用是重写 path 地址;
添加 pathRewrite 选项之前,代理转发完整 pathhttp://127.0.0.1:3000/api/user, 显然这不符合我们后端请求地址;
添加 pathRewrite 选项后,得到请求地址为 http://127.0.0.1:3000/user 这样得到正确的请求地址

关于 webpack-dev-server 的介绍点击这里

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题