Vue 执行npm run build 之后没法跨域 速求指点

npm start直接运行项目 发送请求没问题 但是执行执行npm run build 之后点击dist文件夹下的index.html 就会出现跨域问题
这是springboot @CrossOrigin进行跨域

@CrossOrigin
@MapperScan(value = "com.wflg.springboot.mapper") 
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
    }
}

这是vue 的vue.config.js

module.exports = {
    publicPath:'./',
    //indexPath:'xxx.html',
    pages: {
        index: {
            // page 的入口
            entry: 'src/main.js',
            // 模板来源
            template: 'public/index.html',
            // 在 dist/index.html 的输出
            filename: 'index.html',
        },
    },
    // 配置 webpack-dev-server 行为。
    devServer: {
        open: true,
        port: 8082,
        proxy: {
            '/api': {
                target: 'http://localhost:8080',   //代理接口
                changeOrigin: true, //支持跨域
                pathRewrite: {
                    '^/api': ''    //代理的路径
                }
            }
        },
    },
};

这是 axios

axios.defaults.timeout = 5000;
axios.defaults.baseURL = '/api'

//添加请求拦截器
axios.interceptors.request.use(
    config => {
        return config
    },error => {
        return Promise.reject(error)
    }
);

报错
Access to XMLHttpRequest at 'http://localhost:8080/LoginStu' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

阅读 6k
5 个回答

直接点击dist里的html,路径是D:A/B/C/XX.html,从D:A/B/C/XX.html请求localhost当然跨越,怎么着不得启动个服务,托管下dist目录。。。。

新手上路,请多包涵

vue.config.js中配的代理只有本地开发的时候有用,打包之后就没用了,需要在nginx.conf配置文件里面配置代理,或者是直接让后端配置跨域

新手上路,请多包涵

你dev环境下配置的有代理,为啥生产环境不配置一下?配一下nginx啊

你好,跨域的问题最好是让后台解决,前端在本地开发的时候可以自己解决,但是项目上线上线之后还是跨域,就算配置一个nginx也是多此一举,不建议这样。

@CrossOrigin没有尝试过直接挂在@SpringBootApplication上实现全局跨域(百度也没有百度到)

建议题主尝试@CrossOrigin挂在相关controller上或者直接挂在某接口上

    @CrossOrigin
    @GetMapping("/{id}")
    public Account smed(@PathVariable Long id) {
        // sth
    }
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RestController
    @RequestMapping("/sctl")
    public class SctlController {
         // sth
    }

或者配置@Configuration,继承WebMvcConfigurationSuppor重写addCorsMappings

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    static final String[] ORIGINS = new String[]{"GET", "POST", "PUT", "DELETE"};
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
                .maxAge(3600);
    }

}

其他就是尝试通过NGINX避免跨域(大概本人理解是通过nginx代理实现不同域的前后端放在同域下),前端同学不方便可以这样做

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