javascript - How to return other URL requests in node?
巴扎黑
巴扎黑 2017-05-18 10:48:32
0
2
778

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?

巴扎黑
巴扎黑

reply all(2)
小葫芦

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

刘奇

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);
    })
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template