Error:
Failed to load http://xxxx: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
一、首先前端:
用的是axios,安装npm i axios -S
在组件内引入:
import qs from 'qs'
import axios from 'axios'
let reqUrl = 'http://192.168.1.180:93/byxwebsite/api/getNewsByType’;
let reqParams = {
type: 7,
limit:6,
page:1
}
然后在生命周期钩子里发送请求:
mounted(){
axios.post(reqUrl, qs.stringify(reqParams)).then(response => {
this.testStr = response
},error =>{
this.testStr = error
})
},
二、后台也需要做一些操作,允许所有的请求源头,最少也是我们用的需要允许
public void getNewsByType() {
getResponse().addHeader("Access-Control-Allow-Origin", "*");
String callback = getRequest().getParameter("callback");
String type=getPara("type");
Integer page = getParaToInt("page");
Integer limit=getParaToInt("limit");
if(limit==null || limit==0) {
limit=999;
}
if(page==null || page==0) {
page=1;
}
String sql="select * from tb_news where type="+type+" limit "+(page-1)*limit+","+limit;
/*if(limit!=null) {
sql+=" limit "+limit;
}*/
List<TbNews> list=TbNews.dao.find(sql);
Map<String,Object> map = new HashMap<>();
map.put("data", list);
String jsonp = callback+"("+ JsonKit.toJson(map)+")";//返回的json 格式要加callback()
renderJson(jsonp);
}