天天看点

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:

egg(十八):使用ctx.body接口获取不到返回值具体发现问题的地方:分析原因:具体解决办法:加一个异步方法
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',
	}
​
           

到此就结束了!

继续阅读