电影数据获取
1.使用豆瓣电影API接口
https://douban.uieee.com/v2/movie/top250
小程序不能直接访问此接口,因此需要搭建服务器来访问
2.搭建服务器
(1)创建server文件夹
需要两个文件放置
var express = require("express"); var app = express(); // 代理 var proxy = require("http-proxy-middleware"); var cors = require("cors"); var apiproxy = [ proxy("/", { target: "https://douban-api.uieee.com", changeOrigin: true }) ]; app.use(cors()); app.use((req, res, next) => { req.headers = { "accept": "*/*", "accept-encoding": "gzip, deflate, sdch, br", "accept-language": "zh-CN,zh;q=0.8", "cache-control": "no-cache", "connection": "keep-alive", "host": "localhost:5000", "origin": "http://localhost:8080", "pragma": "no-cache", "referer": "http://localhost:8080/", "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" } next(); }); app.use((req, res, next) => { console.log(req.headers.referer); next(); }) app.use(apiproxy); app.listen(8888, () => { console.log("port on 8888") });
{ "devDependencies": { "cors": "^2.8.4", "express": "^4.16.3", "http-proxy-middleware": "^0.18.0" } }
(2)在server文件夹的命令行窗口中安装插件,执行index.js
ps:如果node/npm不是内部命令的话,需要下载node然后配置它
3.在movie.js中调用函数http
// pages/movie/movie.js var utils = require("../../utils/utils.js"); Page({ /** * 页面的初始数据 */ data: { }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { utils.http("http://localhost:8888/v2/movie/top250",this.getMovies) }, getMovies:function(data){ console.log(data); } })
函数http在utils中的utils.js中实现复用
4.utils.js
utils.js
根据API查看请求实例代码:
5.达成查询数据效果
请发表评论