我正在尝试返回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
时,我也正在恢复正确的身体,但返回不起作用。我做错了什么?
答案 0 :(得分:2)
在调用函数时,您不能在回调中使用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
的结果执行任何操作。