跨域异常可以通过前端或者后端去处理,以下方案二选一即可:
跨域解决方案(前端):
vue.config.js文件新增:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8085/', //接口前缀
ws:true, //代理webSocked
changeOrigin:true, //虚拟的站点需要更管origin
secure: false, //是否https接口
pathRewrite:{
'^/api':'' //重写路径
}
}
}
}
}
修改完以后方法中引入:
axios.defaults.baseURL='/api'
需要重启项目才能生效,方法调用:
created() {
// alert(123)
axios.get("/book-bean/queryBooks").then(function (resp){
console.log(resp)
})
具体解释:传送门
跨域解决方案(后端):
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}