利用豆瓣api写个小程序(小程序笔记)1 利用nodejs调用第三方接口

创建云函数movieList

引入第三方request模块  https://github.com/request/request-promise

在此文件夹下右键用终端打开

npm install --save request
npm install --save request-promise

在index.js里j加载request-promise模块

var rp = require('request-promise');

调用豆瓣api

豆瓣api的调用方式:https://blog.csdn.net/kfgauss/article/details/91492643

总代码如下

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
var rp = require('request-promise');
// 云函数入口函数
exports.main = async (event, context) => {
  return rp(` http://api.douban.com/v2/movie/in_theaters?apikey=0df993c66c0c636e29ecbb5344252a4a&start=${event.start}&count=${event.count}`)


    .then(function (res) {
      // console.log(res);
      return res;
    })
    .catch(function (err) {
      // Crawling failed...
      console.err(err);
    });
}

movie.js

// miniprogram/pages/movie/movie.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    movieList: []
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    this.getMovieList();
  },
  /**
   * 自定义函数
   */
  getMovieList: function () {
    wx.showLoading({
      title: '正在加载。。',
    }),
      wx.cloud.callFunction({
        name: "movieList",
        data: {
          start: this.data.movieList.length,
          count: 4
        }

      }).then(res => {
        console.log(res);
        wx.hideLoading();
        this.setData({
          movieList: this.data.movieList.concat(JSON.parse(res.result).subjects)
        });
      }).catch(err => {
        console.log(err);
        wx.hideLoading();
      })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getMovieList();
  }

})

concat() 方法用于连接两个或多个数组。

arrayObject.concat(arrayX,arrayX,......,arrayX)

JSON.parse()
JSON 通常用于与服务端交换数据。

在接收服务器数据时一般是字符串。

我们可以使用 JSON.parse() 方法将数据转换为 JavaScript 对象。

至于subject。。



movie.wxml

<view class="movie" wx:for="{{movieList}}" wx:key="{{index}}">
  <image  class="movie-img" src="{{item.images.small}}"></image>
  <view class="movie-info">
    <view class="movie-title">{{item.title}}</view>
    <view>评分:
    <text class="movie-score"> {{item.rating.average}}</text>
    </view>
    <view> 主演:
      <text wx:for="{{item.casts}}">{{item.name}} </text>
    </view>
    <view>年份:{{item.year}}</view>
  </view>
</view>

movie.wxss

/* miniprogram/pages/movie/movie.wxss */
.movie{
  height: 300rpx;
  display: flex;
  padding: 10px;
  border-bottom: 1px solid #ccc;

}
.movie-img{
  width: 200rpx;
  height: 100%;
  margin-right:20rpx; 
}
.movie-info{
  flex: 1;
}
.movie-title{
  color: #666;
  font-size: 40rpx;
  font-weight: bolder;
}
.movie-score{
  color: #faaf00;
}

获得效果图

原文地址:https://www.cnblogs.com/polax/p/11536385.html