安裝一下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...
});
這樣就可以獲取到我們需要的信息了