vue项目解决axios跨域问题

1、在项目根目录新建vue.config.js文件

新版本的vuecli已经不会默认添加vue.config.js文件,需要手动创建。

2、编辑vue.config.js

将以下文件添加至vue.config.js中

module.exports = {
  devServer: {
    host: '0.0.0.0',
    open: true,
    proxy: {
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      '/api': {
        target: `http://localhost:18080/`,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    disableHostCheck: true
  }
}

3、效果

  • 所有以/api开头的请求都会默认访问http://localhost:18080/,虽然浏览器中显示的还是localhost:前端端口/api/xx,但是真正访问的其实是http://localhsot:18080/xx
  • 如果想保留/api,可以在pathRewrite'^/api': ''修改为'^/api': '/api'
  • 如果想代理所有请求,可以将proxy内的'/api'修改为/,将pathRewrite内的'^/api': ''修改为'^/': ''

Java代码解决跨域

增加以下配置类

package cn.xxx.xxx.xxx;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/** 跨域配置 */
@Configuration
public class CorsConfig {
  private CorsConfiguration buildConfig() {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    // 1 设置访问源地址
    corsConfiguration.addAllowedOrigin("*");
    // 2 设置访问源请求头
    corsConfiguration.addAllowedHeader("*");
    // 3 设置访问源请求方法
    corsConfiguration.addAllowedMethod("*");
    return corsConfiguration;
  }

  @Bean
  public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // 4 对接口配置跨域设置
    source.registerCorsConfiguration("/**", buildConfig());
    return new CorsFilter(source);
  }
}