困扰了近半个月的跨域问题解决了。
服务端是Springboot,前端是Vue
服务端地址是:http://localhost:8066
前端地址是:http://localhost:6006
前端发送请求使用的是axios,之前设置的baseURL是 process.env.BASE_API, 这个baseURL我在别的地方没有指定,因此是空,后来发现静态图片一直加载不上,我把baseURL重新设置正确为:process.env.API,在quasar.conf.js中设置了对应的初始化值: ctx.dev
build: {
scopeHoisting: true,
// vueRouterMode: 'history',
// vueCompiler: true,
// gzip: true,
// analyze: true,
// extractCSS: false,
env: ctx.dev
? { // so on dev we'll have
API: JSON.stringify('http://localhost:8066')
}
: { // and on build (production):
API: JSON.stringify('http://69.171.69.13:3000')
},
extendWebpack (cfg) {
cfg.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /node_modules/
})
cfg.resolve.alias = {
...cfg.resolve.alias, // This adds the existing alias
// Add you own alias like this
'@': resolve('src')
}
}
},
之后,静态内容还是不能正确加载,此时报错为:
quasar.ios.esm.js?03a0:6 OPTIONS http://localhost:8066/article/all 403
Access to XMLHttpRequest at 'http://localhost:8066/article/all' from origin 'http://localhost:6006' 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.
这就是跨域的问题了,在查找网上的解决办法后,犹犹豫豫一直没觉得是后端的问题,便一直在VUE这块设置请求的参数头header
因为用的是quasar,和正常的vue的es6配置文件不一样,网上也没参考的例子,便一直在尝试琢磨,其中一些参考的设置如下,虽然最后都没用,不过以后别的地方可能会用到(本地设置过后台以后,不需要此设置):
service.interceptors.request.use(config => {
// 加上权限过滤,发送请求前 的操作
const token = authGate.getToken() //获取token,没用的话 可以去掉
config.headers['Access-Control-Allow-Origin'] = '*'
config.headers['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type'
config.headers['Access-Control-Allow-Methods'] = 'PUT,POST,GET,DELETE,OPTIONS'
config.headers['Authorization'] = token
return config
}, error => {
// 过滤掉错误请求后 的操作
console.log(error)
return Promise.reject(error)
})
我在前端写来写去,始终没有解决问题,于是便开始从后端着手,第一次处理就搞定了。
后台Springboot在启动项中添加CorsFilter的过滤器,在前端发送请求的时候自动处理跨域的请求。
具体的跨域过程本文就不阐述了,网上好多都有写:
public class ZstApplication {
public static void main(String[] args) {
SpringApplication.run(ZstApplication.class, args);
}
@RequestMapping(value = "/",method = RequestMethod.GET)
public String index(){
return "index page";
}
@Bean
public CorsFilter corsFilter(){ //设置跨域
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(source);
}
}
这样便可以正常处理静态图片和文件,也可以正常访问了。
Vue前端不用做任何改变。
原文链接:https://ithinkcry.cn/blog/view/detail/2c9ad8cc67a2e91f01680a1ac8af0007
我的个人公众号