标签:数组 ken utils ret art referer val mac os 一个
接口是从网上查找的,看样子应该是微信小程序里面扣出来的(ua 里面有 wechatdevtools)
接口都需要设置apiKey(054022eaeae0b00e0fc068c0c0a2102a)和 ua(Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 wechatdevtools/1.02.1902010 MicroMessenger/6.7.3 Language/zh_CN webview/ token/7858b5b98372a805690a212c8a57f80f),否则会返回错误
fetch('https://frodo.douban.com/api/v2/subject_collection/movie_showing/items?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 wechatdevtools/1.02.1902010 MicroMessenger/6.7.3 Language/zh_CN webview/'
}
}).then(response => {
return response.json();
}).then(data => {
console.log('获得数据:',data);
}).catch(error => {
alert('error:' + JSON.stringify(error));
});
在 src 目录创建 utils 目录,再在里面创建 ajax.js 统一管理应用的 fetch 请求,实现步骤如下:
1.先声明 url 和 apiKey 常量
const baseUrl = 'https://frodo.douban.com/api/v2';
const apiKey = '054022eaeae0b00e0fc068c0c0a2102a';
2.将 fetch 封装成xhr方法,方便使用是调用:
const xhr = (pathname, method, params, headers) => {
return new Promise((res, rej) => {
let url = ~pathname.indexOf('https://') ? pathname : (baseUrl + pathname);
//拼接
let requestBody = {
method: method,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 wechatdevtools/1.02.1902010 MicroMessenger/6.7.3 Language/zh_CN webview/',
...headers
},
body: JSON.stringify(params)
}
if (method === 'GET' && params) {
if (params.id && ~pathname.indexOf('$id')) {
url = url.replace('$id', params.id);
delete params.id;
}
let urlSearch = JSON.stringify(params).replace(/{|}|\"/ig, '').replace(/,/g, '&').replace(/:/g, '='); //将object转换成xxx=yyy&xxx=yyy这样的字符串
url = urlSearch ? `${url}?${urlSearch}&apiKey=${apiKey}` : `${url}?apiKey=${apiKey}`;
delete requestBody.body;
}
fetch(url, requestBody).then(response => {
return response.json();
}).then(data => {
res(data);
}).catch(error => {//暂时还不走到会出现哪些错误,暂时就先把错误弹出
alert('error:' + JSON.stringify(error));
});
})
}
3.调用 xhr,导出 ajax 供其他模块使用,ajax 返回值是 xhr 返回的一个 Promise 对象
const ajax = (pathname, data, headers) => {
return xhr(...apis[pathname], data, headers)
}
export default ajax;
调用时就非常方便了,也不用写 catch ,因为我们可以在 xhr 里面统一管理错误
ajax(pathname, data, headers).then(res => { xxxx });
4.处理 ...apis[pathname]
我们在 apis 里集中管理数据请求,get(pathname) 和 post(pathname) 方法需要返回 [pathname,method]
const apis = {
showing: get('/subject_collection/movie_showing/items'),
detail: get('/movie/$id'),
login:post('https://accounts.douban.com/j/wxa/login/basic')
};
5.添加 get 和 post 方法
通过解构赋值的方式声明 get 与 post,如果后面还有其他类型的methods,如 put 之类的也可以继续在数组里面添加变量。
method 方法参数为 method,返回一个 function ,这个 function 参数为 pathname,最终就可以返回一个包含 pathname、method 的数组。
const method = method => pathname => [pathname, method];
const [get, post] = ['GET', 'POST'].map(value => method(value));
6.最终代码:
const baseUrl = 'https://frodo.douban.com/api/v2';
const apiKey = '054022eaeae0b00e0fc068c0c0a2102a';
const xhr = (pathname, method, params, headers) => {
return new Promise((res, rej) => {
let url = ~pathname.indexOf('https://') ? pathname : (baseUrl + pathname);
let requestBody = {
method: method,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 wechatdevtools/1.02.1902010 MicroMessenger/6.7.3 Language/zh_CN webview/',
...headers
},
body: JSON.stringify(params)
}
if (method === 'GET' && params) {
if (params.id && ~pathname.indexOf('$id')) {
url = url.replace('$id', params.id);
delete params.id;
}
let urlSearch = JSON.stringify(params).replace(/{|}|\"/ig, '').replace(/,/g, '&').replace(/:/g, '='); //将object转换成xxx=yyy&xxx=yyy这样的字符串
url = urlSearch ? `${url}?${urlSearch}&apiKey=${apiKey}` : `${url}?apiKey=${apiKey}`;
delete requestBody.body;
}
fetch(url, requestBody).then(response => {
return response.json();
}).then(data => {
res(data);
}).catch(error => {//暂时还不走到会出现哪些错误,暂时就先把错误弹出
alert('error:' + JSON.stringify(error));
});
})
}
const method = method => pathname => [pathname, method];
const [get, post] = ['GET', 'POST'].map(value => method(value));
const apis = {
//首页
showing: get('/subject_collection/movie_showing/items'),
hot: get('/subject_collection/movie_hot_gaia/items'),
tv: get('/subject_collection/tv_hot/items'),
variety: get('/subject_collection/tv_variety_show/items'),
book: get('/subject_collection/book_bestseller/items'),
music: get('/subject_collection/music_single/items'),
//详情
detail: get('/movie/$id'),
photos: get('/movie/$id/photos')
};
const ajax = (pathname, data, headers) => {
return xhr(...apis[pathname], data, headers)
}
export default ajax;
import ajax from '../utils/ajax';
...
ajax('detail', {//获取详情
id: 1291561
}).then(value => {
console.log(value);
})
...
ajax('showing', {//获取热映列表
start: 0,
count: 20
}).then(value => {
console.log(value);
})
...
React Native 开发豆瓣评分(四)集中管理 fetch 数据请求
标签:数组 ken utils ret art referer val mac os 一个
原文地址:https://www.cnblogs.com/hl1223/p/11112673.html