React Native 开发豆瓣评分(四)集中管理 fetch 数据请求
豆瓣评分的API接口
接口是从网上查找的,看样子应该是微信小程序里面扣出来的(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),否则会返回错误
首页接口
- 热映:https://frodo.douban.com/api/v2/subject_collection/movie_showing/items?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 热门:https://frodo.douban.com/api/v2/subject_collection/movie_hot_gaia/items?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 电视:https://frodo.douban.com/api/v2/subject_collection/tv_hot/items?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 综艺:https://frodo.douban.com/api/v2/subject_collection/tv_variety_show/items?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 图书:https://frodo.douban.com/api/v2/subject_collection/book_bestseller/items?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 单曲:https://frodo.douban.com/api/v2/subject_collection/music_single/items?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a
榜单接口
- 电影榜单:https://frodo.douban.com/api/v2/movie/rank_list?apiKey=054022eaeae0b00e0fc068c0c0a2102a Referer=https://servicewechat.com/wx7f4c4随机数就行
- 读书榜单:https://frodo.douban.com/api/v2/book/rank_list?apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 榜单详情:https://frodo.douban.com/api/v2/subject_collection/movie_weekly_best/items?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a
个人中心接口
- 密码登录:https://accounts.douban.com/j/wxa/login/basic POST header {content-type:application/x-www-form-urlencoded; charset=UTF-8} body:{name,password,apikey}
电影详情接口
- 电影详情:https://frodo.douban.com/api/v2/movie/1291561?apiKey=054022eaeae0b00e0fc068c0c0a2102a* Referer=https://servicewechat.com/wx7f4c4随机数就行
- 剧照: https://frodo.douban.com/api/v2/movie/1291561/photos?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 短评: https://frodo.douban.com/api/v2/movie/1291561/interests?start=0&count=4&status=done&apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 影评: https://frodo.douban.com/api/v2/movie/1291561/reviews?start=0&count=20&apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 同类推荐:https://frodo.douban.com/api/v2/movie/1291561/recommendations?apiKey=054022eaeae0b00e0fc068c0c0a2102a
- 电影与用户关系(是否评论):https://frodo.douban.com/api/v2/user/159766151?apiKey=054022eaeae0b00e0fc068c0c0a2102a header {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/ token/7858b5b98372a805690a212c8a57f80f} token 通过登录获得
封装 fetch 请求
使用 fetch 获取数据示例:
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方法,方便使用是调用:
- 参数为 pathname, method, params, headers
- fetch 的 url 有 baseUrl + pathname 组成,但是实际从中可能有打点上报或其他三方接口,所以 pathname 如果含有 https 就不进行拼接
- requestBody 中,headers 默认有 Content-Type 和 User-Agent,如果使用时还传入了 header 则继续添加传入的header
- requestBody 的 body 必需是字符串,传入的 params 是 object 类型,需要将其 JSON.stringify
- 如何请求为 get 请求,那么 requestBody 中就不能有 body,需要将参数拼接到 url 后面
- 由于 get 接口有两种类型:https:xxx.com?xxx=xxx&xxx=xxx 和 https:xxx.com/id/xxx?xxx=xxx&xxx=xxx,第一种,直接 JSON.stringify(params) 拼接到 url 末尾,第二种,则 约定 id 为 $id,将 params 参数里面的 id 的值替换 $id。
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 数据请求的更多相关文章
- React Native 开发豆瓣评分(八)首页开发
首页完成效果展示: 一.开发占位图组件 在没有数据的时候使用占位图替代 items 的位置. 在 components 目录里创建 moviesItemPlaceholder.js import Re ...
- React Native 开发豆瓣评分(五)屏幕适配方案
前言 React Native 是以实际像素 dp 为单位的,这导致在不同分辨率的屏幕会有不一样的显示情况. 在原生 Android 中,可以根据不同的分辨率添加不同的样式目录,以解决不同分辨率的问题 ...
- React Native 开发豆瓣评分(一)环境搭建&配置模拟器
详细可参考 官方文档,这里进记录一些重要过程. 安装环境 下载 Android Studio 选择 Custom 进行安装: Android SDK Android SDK Platform Perf ...
- React Native 开发豆瓣评分(三)集成 Redux
什么是 redux redux 是一个用于管理 js 应用状态(state)的容器.比如组件 A 发生了变化,组件 B 要同时做出响应.常见的应用场景就是用户的登录退出操作:未登录状态,个人中心显示登 ...
- React Native 开发豆瓣评分(七)首页组件开发
首页内容拆分 看效果图,首页由热门影院.豆瓣热门.热门影视等列表组成,每个列表又由头加横向滑动的 电影海报列表构成. 所以可以先把页面的电影海报.评分.列表头做成组件,然后在使用 ScrollView ...
- React Native 开发豆瓣评分(二)路由配置
路由管理使用官方推荐的 React Navigation; 配置环境 安装相关依赖 yarn add react-navigation react-native-gesture-handler Lin ...
- React Native 开发豆瓣评分(六)添加字体图标
添加依赖 yarn add react-native-vector-icons Link 依赖 react-native link react-native-vector-icons 使用默认字体图标 ...
- React Native开发入门
目录: 一.前言 二.什么是React Native 三.开发环境搭建 四.预备知识 五.最简单的React Native小程序 六.总结 七.参考资料 一.前言 虽然只是简单的了解了一下Reac ...
- React Native开发技术周报2
(1).资讯 1.React Native 0.22_rc版本发布 添加了热自动重载功能 (2).技术文章 1.用 React Native 设计的第一个 iOS 应用 我们想为用户设计一款移动端的应 ...
随机推荐
- 啃OBS源码-界面汉字
插件对应该字体目录:D:\project\vs\obs\obsstudio21.12\build\rundir\Debug\data\obs-plugins obs对应该字体目录:D:\project ...
- 算法名称 Alias Method
public class AliasMethod { /* The probability and alias tables. */ private int[] _alias; private dou ...
- PAT 甲级 1079 Total Sales of Supply Chain (25 分)(简单,不建树,bfs即可)
1079 Total Sales of Supply Chain (25 分) A supply chain is a network of retailers(零售商), distributor ...
- IISExpress.无法启动IIS Express Web 服务器.Starting IIS Express... IIS Express is running
x 提示: 无法启动IIS Express Web 服务器. 来自IIS Express的输出: Starting IIS Express... IIS Express is running 总结: ...
- cpu多级缓存
CPU cache: CPU的频率太快,主存跟不上,在处理器时钟周期内,CPU需要等待主存,浪费资源.cpu cache的出现,缓解了cpu与主存之间速度不匹配的问题. CPU cache的特性: 1 ...
- xshell修改配色方案为白色
- [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树
Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...
- Java高级面试题整理(附答案)
这是我收集的10道高级Java面试问题列表.这些问题主要来自 Java 核心部分 ,不涉及 Java EE 相关问题.你可能知道这些棘手的 Java 问题的答案,或者觉得这些不足以挑战你的 Java ...
- Spring boot后台搭建二集成Shiro添加Remember Me
上一片文章实现了用户验证 查看 当用户成功登录后,关闭浏览器,重新打开浏览器访问http://localhost:8080,页面会跳转到登录页,因为浏览器的关闭后之前的登录已失效 Shiro提供了R ...
- 【编程开发】x86,I386,i686, x86_64, x64,amd64、Windows Linux AIX下查看CPU位数和操作系统位数、rpm包名
a2ps-4.13b-57.2.el5.i386.rpm 每一个rpm包的名称都由"-"和"."分成了若干部分.就拿 a2ps-4.13b-57.2.el5.i ...