[ionic开源项目教程]

时间:2022-08-06 08:54:13

[ionic开源项目教程] 第14讲 使用jsonp解决跨域问题

相信很多朋友在开发中都会遇到以下这个问题。

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

[效果图]

之前开发中都是用google的插件Access-Control-Allow-Origin来实现的跨域,地址是:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related(需要fq)。
其实这个项目的后台接口是支持jsonp的请求的,所以这一讲将项目中所有的请求都改为jsonp的方式。
这一讲的改动都在service

将所有的请求都改为$http.jsonp,在url最后拼接一个参数&callback=JSON_CALLBACK,如下:

 .service('BaseService', function ($http) {
this.loadMore = function ($this) {
console.log(
"正在加载更多数据..." + $this.page);
$http.jsonp($
this.url + "?page=" + $this.page + "&rows=" + settings.rows + "&callback=JSON_CALLBACK").success(function (response) {
console.log(response);
if (response.tngou.length > 0) {
$
this.items = $this.items.concat(response.tngou);
$
this.page++;
}
else {
console.log(
"没有数据了...")
$
this.isload = true;
}
$
this.callback();
});
}
this.doRefresh = function ($this) {
console.log(
"正在执行refresh操作...");
//使用jsonp的方式请求
$http.jsonp($this.url + "?page=1&rows=" + settings.rows + "&callback=JSON_CALLBACK").success(function (response) {
console.log(response);
$
this.page = 2;
$
this.items = response.tngou;
$
this.callback();
$
this.isload = false;
});
}
})

 

注意:

  • 在使用jsonp请求方式之前,请确认服务器接口是否支持jsonp请求。
  • 这里只贴出了BaseService的代码,其他地方自己试着改改。