云音乐小程序管理系统(三)—— HTTP API触发云函数获取歌单列表

安装一下koa的路由npm install koa-router

使用MVC的思想,将前端操作文件都存放在controller中,将前端请求和调用都存放在其中

一、请求路由

在我们的入口文件app.js中导入路由信息和歌单请求文件

//导入文件
const playlist=require('./controller/playlist.js')
//声明路由
router.use('/playlist', playlist.routes())

app.use(router.routes())
app.use(router.allowedMethods())

在歌单请求文件中,使用路由,请求歌单的地址
在这里插入图片描述
是的可以在前端中获取歌单信息。

最后让我们来完善路由信息,来请求歌单列表

首先获取我们的url(规则在官方文档)(地址使用反引号)

const URL=`https://api.weixin.qq.com/tcb/invokecloudfunction?access_token=${access_token}&env=${ENV}&name=music`

具体每个属性看文档要求,之后因为使用的是request的POST请求

可以在github中查看request——request-promise的POST的使用方法来获取我们要使用的云函数

    //发送post请求
    var options = {
        method: 'POST',
        uri: URL,
        body: {
            $url:'playlist', //函数路由名字
            start:0,  //开始数
            count:50 //每次读取数
        },
        json: true // Automatically stringifies the body to JSON
    };
    
    ctx.body=await rp(options)
        .then( (res)=>{
            console.log(res)
            return JSON.parse(res.resp_data).data //获取返回的值得内容,变为JSON字符串
        })
        .catch(function (err) {
            // POST failed...
        });

这样就可以获取到我们需要的信息了
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章