spring boot 解决Ajax 跨域问题

Ajax 跨域 请求 spring boot 的跨域问题

Ajax 跨域请求spring boot 时 前端报错

报错
出现跨域错误

后端代码
 @RequestMapping("/getArticles")
    @ResponseBody
    public JSONObject toArticle(@RequestParam(value = "page") int currentPage){
        if(currentPage == 0){currentPage = 1;}
        JSONObject jsonObject = new JSONObject();
        ArticlePage articlePage = new ArticlePage(currentPage,10);
        Page<Article> page = articleServiceImp.getUserPageWrapperPage(articlePage);
        List<Article> articleList = page.getRecords();
        jsonObject.put("articles", articleList);
        jsonObject.put("page", 1);
        jsonObject.put("code",200);
        jsonObject.put("status",constantPool.success);
        return jsonObject;
    }
前端代码
$.ajax({
            url:"http://127.0.0.1:8080/getArticles?page="+page,
            methed:"post",
            success: function (data) {
                    console.log(data)
                     //假设你的列表返回在data集合中
                    layui.each(data, function(index, item){
                    lis.push('<li>'+ item.title +'</li>');
                    }); 
        //执行下一页渲染,第二参数为:满足“加载更多”的条件,即后面仍有分页
        //pages为Ajax返回的总页数,只有当前页小于总页数的情况下,才会继续出现加载更多
            next(lis.join(''), page < res.pages);    
            },
            error:function(res){

            }
        })

问题比较简单 但是也比较折磨

解决方法

你没看错 就是加一个 @CrossOrigin 注解

 @RequestMapping("/getArticles")
    @ResponseBody
    @CrossOrigin
    public JSONObject toArticle(@RequestParam(value = "page") int currentPage){
        if(currentPage == 0){currentPage = 1;}
        JSONObject jsonObject = new JSONObject();
        ArticlePage articlePage = new ArticlePage(currentPage,10);
        Page<Article> page = articleServiceImp.getUserPageWrapperPage(articlePage);
        List<Article> articleList = page.getRecords();
        jsonObject.put("articles", articleList);
        jsonObject.put("page", 1);
        jsonObject.put("code",200);
        jsonObject.put("status",constantPool.success);
        return jsonObject;
    }

已解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值