React 获取服务器API接口数据:axios、fetchJsonp
使用axios、fetchJsonp获取服务器的接口数据。其中fetchJsonp是跨域访问
一、使用axios
1、安装axios模块
npm install --save axios
2、引用模块
import axios from 'axios'
3、实现请求
import axios from 'axios';
const request = (url: string, params = {}, data = {}, options) => { // debug(url, params);return new Promise((resolve, reject) => { axios({url, params, data, ...options}) .then((response) => { // debug(response); // 请求返回为json格式, 则response.data必须为对象,且必须有固定的格式, // 这里没有处理返回值为字符串的情况, 目前没有这样的需求 reject(response); }) .catch((error) => { debug(error); reject(error); }); }); }; export function get (url: string, params?: any, options?: any) { return request(url, params, undefined, {method: 'get', ...options}); } export function post (url: string, data?: any, options?: any) { return request(url, undefined, data, {method: 'post', ...options}); }
//这段代码还没有经过测试,如果不行可以尝试下面代码
request = (url) => {
axios.get(url)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
}
二、使用fetchJsonp
1、安装fetchJsonp模块
npm install --save fetchJsonp
2、引用模块
import fetchJsonp from 'fetch-jsonp';
3、使用(还没有测试的)
import fetchJsonp from 'fetch-jsonp';
jsonp (url: string, callback = null) { return new Promise((resolve, reject) => { fetchJsonp(url, {callback}) .then((res) => { resolve(res); }) .catch((err) => { debug(err); }) }) }
这里说下fetchJsonp的问题
在代码中应该使用script标签,引用js文件
let script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'http://192.168.1.100:7700/Advert/GetAdvert?elementId=adid'; document.getElementById(this.props.htmlId).appendChild(script);
<div id={this.props.htmlId} style={this.props.styles}></div>
下面代码是接口http://192.168.1.100:7700/Advert/GetAdvert?elementId=adid返回的信息,其实是向代码中插入一个函数,自动运行,类似前端调用函数
(function(){ var json = {"AdvertName":"图片广告","AdvertDesc":"图片广告","AdvertHeight":"100%","AdvertId":63102,
"AdvertImage":"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=831914849,3674285067&fm=11&gp=0.jpg",
"AdvertWidth":"100%","JumpUrl":"http://192.168.2.88:7700/advert/JumpAdvert?advertId=63102&flowerId=1987&orderMark=7c3a8f5172494fcab09e5eee607aae66&merchantCode=",
"AdvertWord":"图片广告"};
var elementId = ''; var div = document.createElement("div"); div.setAttribute div.style.width = "100%"; div.style.overflow = "hidden"; var img = document.createElement("img"); img.src = json.AdvertImage; img.style.maxWidth="100%"; img.onclick = function(){location.href=json.JumpUrl;} div.appendChild(img); if(elementId == '') { var scripts = document.getElementsByTagName("script"); var script = scripts[scripts.length - 1]; var dom = script.parentNode; dom.removeChild(script); dom.appendChild(div); } else { var dom = document.getElementById(''); dom.appendChild(div); } div = null; img = null; scripts = null; script = null; dom = null; })();
fetchJsonp也类似这样,它使用的window[function_name] = function(){} ,可以查看它的原代码