【问题标题】:Node.js request.post return undefinedNode.js request.post 返回未定义
【发布时间】:2017-01-01 18:44:43
【问题描述】:

我正在尝试在 node.js 中返回另一个站点的发布请求的正文,但下面的函数没有返回任何内容

  // returns "undefined"
  mysqlVerify = (socialclub_id, session_id) => {
      request({
          url: 'http://myapi.site/VerifyUser',
          method: 'post',
          form: {
            socialclub_id: socialclub_id,
            session_id: session_id
          }
      }, (error, response, body) => {
          if(error) {
              return false       // this isnt returning
          } else {
              console.log(response.statusCode, body)
              return body == "1" // this isnt returning
          }
      })
  }

另一个站点正在接收发布请求,当我使用console.log 时,我也得到了正确的正文,但是返回不起作用。我做错了什么?

【问题讨论】:

    标签: javascript mysql node.js return undefined


    【解决方案1】:

    当你的函数被调用时,你不能在回调中使用return 来返回一个值。您可以传递mysqlVerify 一个回调(一个在确定结果后运行的函数)并在收到响应后调用它,如下所示:

    mysqlVerify = (socialclub_id, session_id, callback) => {
        request({
            url: 'http://myapi.site/VerifyUser',
            method: 'post',
            form: {
                socialclub_id: socialclub_id,
                session_id: session_id
            }
        }, (error, response, body) => {
            if(error) {
                callback(false)       // call the function if false
            } else {
                console.log(response.statusCode, body)
                callback(body == "1") // call the function if condition met
            }
        });
    }
    

    然后callback 函数可以使用mysqlVerify 的结果做任何你需要的事情。

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 2021-01-05
      相关资源
      最近更新 更多