跨域: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;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值