跨域:springboot+vue 发送ajax请求
springboot vue 发送ajax请求(跨域问题)
1)修改vue项目的config/index.js里的dev/proxyTable内容
proxyTable: {
// proxy all requests starting with /api to jsonplaceholder
'/api': {//虚拟目录
target: 'http://localhost:3000',//后台NodeSpringboot项目的请求网址
changeOrigin: true,
pathRewrite: {
'^/api': ''//由于上面的虚拟目录实际上是不存在的,不去掉的话访问的时候显示的url会变成'http://localhost:3000/api',所以得去掉
}
}
},
2)在springboot项目的Controller新建一个类
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter{
@Override
public void addCorsMappings(CorsRegistry registry) {
System.out.println("----------------------");
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
3、在vue的页面中ajax请求就好,注意
①url:’http://localhost:8763/aa‘
②controller要加@ResposeBody,因为是接收json,否则报404
(解决方法链接:https://blog.csdn.net/qq_36688143/article/details/82260722)
③ 如果返回值不是json或者list、map等类型格式,只是字符串,那vue那边的ajax会接收不到返回值,无反应
aa: function (event) {
$.ajax({
type:'POST',
url:'http://localhost:8763/aa',
/* 要不要都可以
headers:{
"Conten-Type":"http://localhost:3000/"
},*/
data:{
},
success:function (backDate) {
console.log('666');
console.log(backDate);
}
})
},
4、后台controller接收请求
@ResponseBody
@RequestMapping(value = {"/aa"},produces = {"application/json;charset=UTF-8"},method = RequestMethod.POST)
public List aa(){
List<UserInfo> list = userService.findAllUser();
System.out.println("后台接收ajax请求:"+list.size());
return list;
}
还没有评论,来说两句吧...