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.
@CrossOrigin没有尝试过直接挂在@SpringBootApplication上实现全局跨域(百度也没有百度到)
建议题主尝试@CrossOrigin挂在相关controller上或者直接挂在某接口上
或者配置@Configuration,继承WebMvcConfigurationSuppor重写addCorsMappings
其他就是尝试通过NGINX避免跨域(大概本人理解是通过nginx代理实现不同域的前后端放在同域下),前端同学不方便可以这样做