java后台+vue前端,解决jsonp跨域问题(有数据返回的,但是Response的body或者data为空)

版权声明:转发请标注原文地址 https://blog.csdn.net/hyt941026/article/details/82148368

 前端Vue采用jsonp方法访问后台数据

前端请求代码:

getAllList() {
	//导入Vue-resource.js,通过this.$http发起数据请求
	//this.$http.get('url').then(function(result){})
	//通过then指定回调函数,可获取服务器返回的数据
	//判断result.status是否等于200,200为请求成功。
	//若是0,则将result.body赋值给this.list。若不是则提示获取数据失败
				
this.$http.jsonp('http://localhost:8080/VueServer/server')
    .then(function(result) {
        console.log(result)//便于查看数据返回情况
	    if(result.status === 200) {
			this.list = result.body
		} else {
			alert('获取数据失败')
		}
     })
}

后台servlet主要代码:


protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setHeader("content-type", "text/html;charset=UTF-8");
    PrintWriter out;
    out=resp.getWriter();
    out.write("[{id:1, name:'奔驰'},{id:2, name:'宝马'}]");
}

 在控制台Network查看,该请求是有数据返回的,但是Response的body或者data为空,状态码status为0

原因是jsonp在发送请求的时候在URL后面自动添加了 一个callback参数,而而我们没有把这个参数返回导致Response无数据

解决方法:

在后台获取callback的值并将其与返回数据拼接后一起放回

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setHeader("content-type", "text/html;charset=UTF-8");
    PrintWriter out;
    out=resp.getWriter();
    //获取callback值与需要返回的数据拼接,一并返回给前端。注意需要返回的数据需要用小括号“()”包裹起来
    out.write(req.getParameter("callback") + "([{id:1, name:'奔驰'},{id:2, name:'宝马'}])");
    }

 这样前端就可以准确获取数据了,如图

 

猜你喜欢

转载自blog.csdn.net/hyt941026/article/details/82148368
今日推荐