在开发时候 新建 vue.config.js文件,位置如下:
内容如下:
module.exports = {
devServer: {
open: true,
host: 'localhost',
port: 8080,
https: false,
//以上的ip和端口是我们本机的;下面为需要跨域的
proxy: { //配置跨域
'/shiro': { // 这里和方法里 axios里的 url匹配 (本行为第9行)
target: 'http://localhost:9090/shiro/', //这里后台的地址模拟的;应该填写你们真实的后台接口 // 这里和后台地址完全匹配
ws: true,
changOrigin: true, //允许跨域
pathRewrite: {
'^/shiro': '' //请求的时候使用这个api就可以 // 这里和 第9行匹配
}
}
}
},
configureWebpack: {
performance: {
hints: 'warning',
//入口起点的最大体积
maxEntrypointSize: 50000000,
//生成文件的最大体积
maxAssetSize: 30000000,
//只给出 js 文件的性能提示
assetFilter: function(assetFilename) {
return assetFilename.endsWith('.js');
}
}
},
publicPath: './',
}
注意: proxy: {}
但是,这样有缺点,这样只能在开发时使用。在开发时,这样调用后台接口即可
this.$axios({
method: "post",
url: "/shiro/sys/login",
data: {
username: this.username,
password: this.password
}
}).then(result => {})
但是项目部署后,就会出现地址找不到。
所以,把上面的代码改为这样即可:
this.$axios({
method: "post",
url: "http://localhost:9090/shiro/sys/login",
data: {
username: this.username,
password: this.password
}
}).then(result => {})
不过这样做之后,在后端就得要加个配置类了。新建 WebMvcConfiguration类,写上如下内容:
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
// registry.addMapping("**")
.allowedOrigins("*")
.allowedMethods("POST", "GET","PUT", "DELETE")
.allowCredentials(true)
.allowedHeaders("*")
.maxAge(3600);
}
}
即可解决跨域问题。