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;
}
已解决