search

Home  >  Q&A  >  body text

javascript - How to return other URL requests in node?

I want to encapsulate the token method. Why can’t this call be returned correctly?

app.js

app.use('/getUserInfo',function(req,res,next){
    console.log("进入getUserInfo")
    utils.getToken(appid,appsecret)
})

utils.js

utils.getToken=function(appid,appsecret){
    console.log("我是utils里面的")
    let tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
    let jsonResult=''
    return function(){        
        request(tokenUrl,(err,response,body)=>{
            let jsonResult = JSON.parse(body);
            return jsonResult
        })
    }
}

I want to call getUserInfo to obtain user information, how to change it?

巴扎黑巴扎黑2736 days ago766

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-05-18 10:50:32

    utils.getToken(appid,appsecret)() call?

    reply
    0
  • 怪我咯

    怪我咯2017-05-18 10:50:32

    Node is asynchronous. If you can return directly, what else should you do with async/await?

    You can also use callback directly:

    app.use('/getUserInfo',function(req,res,next){
        console.log("进入getUserInfo")
        utils.getToken(appid,appsecret,function(res){
          console.log(res);
        })
    })
    

    ........................

    utils.getToken=function(appid,appsecret,callback){
        console.log("我是utils里面的")
        let tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;  
        request(tokenUrl,(err,response,body)=>{
            let jsonResult = JSON.parse(body);
            callback(sonResult);
        })
    }

    reply
    0
  • Cancelreply