如何从node.js请求调用返回数据? (undefined不是函数)

时间:2022-07-01 19:41:27

I'm pretty sure I'm missing a callback somewhere here:

我很确定我在这里错过了一个回调:

from tools.js:

来自tools.js:

exports.getServerPermalink = function(username, callback) {
requestURL = config.apiServer+ username + myUrl
request(requestURL, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    list = JSON.parse(response.body);
    console.log(list);
    newPermalink = list[0].permalink;
  } else {
    console.log(error);
  }
  callback(null, newPermalink);
  });
}

it's called here, my main file (tools.js is included):

它在这里被称为我的主文件(tools.js包含在内):

newPermalink = tools.getServerPermalink(checkSession.username);
res.redirect('/'+ newPermalink) ;   

but I get the error "undefined is not a function" pointing to

但我得到错误“未定义不是一个函数”指向

      callback(null, newPermalink);

when I try to run it.

当我试图运行它。

Any pointers to examples for the "require" module that don't just console.log stuff would be much appreciated.

任何指向“require”模块的示例的指针,不仅仅是console.log的东西,将非常感激。

2 个解决方案

#1


3  

callback seems to be undefined because you didn't pass it to your modules method

回调似乎未定义,因为您没有将它传递给您的模块方法

should be like this:

应该是这样的:

tools.getServerPermalink(checkSession.username, function(argument, newPermalink){
    res.redirect('/'+ newPermalink) ;
});

Also tools.getServerPermalink()doesn't directly return the url (it does not return anything, as the internal request is asynchronous) but passes it as the second argument to your callback function.

tools.getServerPermalink()也没有直接返回url(它不返回任何内容,因为内部请求是异步的)但是将它作为第二个参数传递给你的回调函数。

#2


0  

your exports.getServerPermalink is a function defined taking 2 arguments but when you call it, you are only passing in one: newPermalink = tools.getServerPermalink(checkSession.username);

你的exports.getServerPermalink是一个定义了2个参数的函数,但是当你调用它时,你只传入一个:newPermalink = tools.getServerPermalink(checkSession.username);

#1


3  

callback seems to be undefined because you didn't pass it to your modules method

回调似乎未定义,因为您没有将它传递给您的模块方法

should be like this:

应该是这样的:

tools.getServerPermalink(checkSession.username, function(argument, newPermalink){
    res.redirect('/'+ newPermalink) ;
});

Also tools.getServerPermalink()doesn't directly return the url (it does not return anything, as the internal request is asynchronous) but passes it as the second argument to your callback function.

tools.getServerPermalink()也没有直接返回url(它不返回任何内容,因为内部请求是异步的)但是将它作为第二个参数传递给你的回调函数。

#2


0  

your exports.getServerPermalink is a function defined taking 2 arguments but when you call it, you are only passing in one: newPermalink = tools.getServerPermalink(checkSession.username);

你的exports.getServerPermalink是一个定义了2个参数的函数,但是当你调用它时,你只传入一个:newPermalink = tools.getServerPermalink(checkSession.username);