前言:
在使用node的egg写接口访问外部数据 和使用superagent-charset 解析中文乱码的时候,发下在函数的回调方法里面,给 ctx.body 赋值是不会成功的,但是可以this.abc 调用其他定义的方法,也可以成功传参,或者console.log 你拿到的数据,都是可以的。
具体发现问题的地方:
现象1:
request.get(url)
.buffer(true)
.charset('gbk')
.end((err, html) => {
const htmlText = html.text
const $ = cheerio.load(htmlText,{ decodeEntities: false })
//在这里,可以console.log 你的数据
//在这里,可以 this.abc() 调用其他接口
//在这里 ctx.body 赋值会失效 ,页面一直提示404
})
现象2:
request(`https://api.weixin.qq.com/sns/jscode2session,function (error, response, body) {
if(error) { //请求异常时,返回错误信息
return reject(error);
} else {
// console.log 数据是可以成功
//ctx.body 是无法成功的
ctx.body = {
code: 0,
msg: '登录成功'
}
}
}
分析原因:
函数的回调都会出现问题
具体解决办法:加一个异步方法
new Promise((resolve, reject) => {
return resolve({
})
})
方法源码1:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLwMjMyYTOwIGOkhzNhVTYhBzYxQzN0MTO1kTM3UTZhVzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
const requestPromise = new Promise((resolve, reject) => {
request.get(url)
.buffer(true)
.charset('gbk')
.end((err, html) => {
const htmlText = html.text
const $ = cheerio.load(htmlText,{ decodeEntities: false })
const imgListData = [];
$('a').each(function () {
let url = $(this).attr('href')
let text = $(this).text()
console.log(url);
console.log(text);
imgListData.push(url);
})
/**
* 处理,保存数据等操作
*/
return resolve({
imgListData,
$,
})
})
})
const result = await requestPromise;
ctx.body = result
方法源码2:
const requestPromise = new Promise((resolve, reject) => {
request(`https://api.weixin.qq.com/sns/jscode2session,
function (error, response, body) {
if(error) { //请求异常时,返回错误信息
return reject(error);
} else {
//返回你的数据
return resolve({
})
}
}
const result = await requestPromise;
// 最后接口返回数据
ctx.body = {
msg: 'ok',
}