问题
前端的代码部分
this.$http.post("/user/register/"+this.username+"/"+this.email+"/"+this.password+"/").then((res)=>{
console.log(res)
});
后端接口
@PostMapping ("/register/{username}/{email}/{password}")
public ServerResponse register(@PathVariable("username") String username,
@PathVariable("email") String email,
@PathVariable("password") String password) {
}
在访问后端接口时,出现了如上图的跨域问题。在csdn上到很多关于跨域问题的解决方法,有些方法并不能解决这个问题,下面讲一下我解决的方法,供大家参考。
解决方法
- 在vue.config.js文件中的添加下面内容:
devServer: {
proxy:{
'/api':{
target: 'http://127.0.0.1:8001', //请求的服务器地址
pathRewrite:{
'^/api':''}, //可以让发过去的请求不带/api打头
}
}
}
其中target指定的是你后端服务器的地址。
- 如果你在使用axios时配置了baseURL属性,如下代码,那么就删掉。
axios.defaults.baseURL='http://localhost:8001'
- 最后在发送请求时,给后端接口加上**/api**,这个是由你在vue.config.js上配置决定的。
值得注意的点:
- 跨域在chrome浏览器中你看到的还是http://localhost:8080(即你启动vue的地址,而不是你服务器应用的地址),所以你看到不要惊讶,其实是跨域成功的。
- http请求中要带上/api,经过index.js的代理会将/api去掉,浏览器中的访问地址为http://localhost:8080/api/user/login,然后实际的访问的地址是http://localhost:8001/user/login。通过代理就实现了跨域访问。