老师,请问当我在请求HTTP API,要求返回playlist信息的时候,总是出现以下错误,而取得TOKEN经测试是没有问题的。
来源:9-5 HTTP API触发云函数获取歌单列表
精慕门0241520
2021-02-09
const Koa = require(‘Koa’)
const app = new Koa()
const Router = require(‘koa-router’)
const router = new Router()
const playlist=require(’./controller/playlist.js’)
router.use(’/playlist’, playlist.routes())
app.use(router.routes())
app.use(router.allowedMethods())
app.use(async (ctx) => {
ctx.body = ‘Hello Wolrd’
})
app.listen(3000, () => {
console.log(‘服务开启在3000端口’)
})
const Router = require(‘koa-router’)
const router = new Router()
const getAccessToken = require(’…/utils/getAccessToken.js’)
const ENV = 'musicwangyiyun-8gf3fss84cdaeca0’
const rp = require(‘request-promise’)
router.get(’/list’, async (ctx, next) => {
const access_token = await getAccessToken()
// console.log(access_token)
const url = https://api.weixin.qq.com/tcb/invokecloudfunction?access_token=${access_token}&env=${ENV}&name=music
const options = {
method: ‘POST’,
uri: url,
body: {
$url: ‘playlist’,
start: 0,
count: 50
},
json: true // Automatically stringifies the body to JSON
};
await rp(options)
.then((res) => {
console.log(res)
})
.catch(function (err) {
// POST failed...
});
ctx.body = '歌单列表'
})
module.exports = router
const APPID = '’
const APPSECRET = '**'
const fs = require(‘fs’)
const path = require(‘path’)
const fileName = path.resolve(__dirname, ‘./access_token.json’)
const rp = require(‘request-promise’)
// console.log(fileName)
const URL = https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}
const updateAccessToken = async () => {
const resStr = await rp(URL)
const res = JSON.parse(resStr)
// console.log(res)
if (res.access_token) {
fs.writeFileSync(fileName, JSON.stringify({
access_token: res.access_token,
createTime: new Date()
}))
} else {
await updateAccessToken()
}
}
const getAccessToken = async () => {
try {
const readRes = fs.readFileSync(fileName, ‘utf8’)
const readObj = JSON.parse(readRes).access_token
console.log(readObj)
const createTime = new Date(readObj.createTime).getTime()
const nowTime = new Date().getTime()
if ((nowTime - createTime) / 1000 / 60 / 60 >= 2) {
await updateAccessToken()
await getAccessToken()
}
return readObj.access_token
} catch (error) {
await updateAccessToken()
await getAccessToken()
}
}
setInterval(async () => {
await updateAccessToken()
}, (7200 - 300) * 1000)
// updateAccessToken()
// // console.log(getAccessToken())
// getAccessToken()
module.exports = getAccessToken
1回答
-
精慕门0241520
提问者
2021-02-10
谢老师,经过我两天苦思(掉了头发),建议你需要修改一下代码,在“
const readObj = JSON.parse(readRes)
”后不可以加入“
access_token
”,会与后面的“
return readObj.access_token
”语句相冲突,否则微信服务端收到的不会是正确的TOKEN,必然报错(40001错误)
022021-04-11
相似问题