egg(十八):使用ctx.body接口获取不到返回值

前言:

        在使用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:

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',
	}
​

到此就结束了!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值