您的位置:首页 > 移动开发 > 微信开发

微信小程序运用云函数调用新闻类API

2020-07-14 05:57 148 查看

微信小程序运用云函数调用新闻类API

微信小程序运用云函数调用新闻类API

在小程序中调用API有调用限制,只能给5个可信域名发送请求,而且需要备案。而在云函数中则不受到这样的限制。所以使用云函数调用API更为好。

新闻列表的编写

云函数的编写

首先要找到一个适合自己程序的api接口。其次再进行云函数的编写。以我找到的api为例。
云函数的名称:newslist是新闻页面的列表

// 云函数入口文件
const cloud = require('wx-server-sdk')
var rp = require('request-promise');
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
return rp(`https://api.isoyu.com/api/News/new_list?type=3&page=5`).then(function (res) {
console.log(res);
return res;
}).catch(function (err) {
console.error(err);
})
}

JS方法

新闻列表的JS方法

onLoad: function (options) {
//引用方法
this.getNewsList();
},
getNewsList: function () {
var that = this
//预加载
wx.showLoading({
title: '加载中',
})
wx.cloud.callFunction({
//云函数的名称
name: 'newslist',
data: {
//云函数中插入数据
}
}).then(res => {
var result = JSON.parse(res.result)
console.log(result.data);
that.setData({
readlist:result.data//写入新闻列表内容
});
// console.log(that.setData);
wx.hideLoading();
}).catch(err => {
console.log(err);
wx.hideLoading();
})
},
//加载新闻详情
goToDetail: function(event){
//获取wxml中data-id中的数据postid
var postid = event.currentTarget.dataset['id'];
//console.log('postid:' + postid);
//页面跳转
wx.navigateTo({
url: '../news/new_detail/new_detail?postid=' + postid
});
},

wxml页面编写

<view wx:for="{{readlist}}" wx:key="item">
<view class='news1' data-id="{{item.postid}}" bindtap="goToDetail">
<view class='news-img'>
<image src="{{item.imgsrc}}" />
</view>
<view class='news-text'>
<view class='news-text-1'>
<text>{{item.title}}</text>
</view>
<view class='news-text-2'>
<text>{{item.ptime}}</text>
</view>
</view>
</view>
</view>

wxss样式

.news1{
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
}
.news-img{
width: 30%;
height: 180rpx;
margin: 2px;
}
.news-img image{
width: 100%;
height: 100%;
}
.news-text{
width: 68%;
height: 180rpx;
}
.news-text-1{
font-size: 18px;
}
.news-text-2{
font-size: 15px;
color: rgba(128, 128, 128, 0.932);
text-align: right;
padding-right: 10rpx;
padding-top: 30rpx;
}
.news-line{
width: 100%;
height: 1px;
background-color: rgba(128, 128, 128, 0.466);
}

最终效果截图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: