如何解决Node.js中的此回调错误?

时间:2019-07-10 20:26:39

标签: node.js rocket.chat

首先,我安装了该库

> npm install rocketchat-api

然后我运行了这段代码以使用rocket.chat REST API

// Node.js code
const RocketChatApi = require('rocketchat-api');
const result='https://rocket.chat/docs/developer-guides/rest-api/users/setavatar';
const userId='A user id';
const avatarUrl='http://www.coca.ir/wp-content/uploads/2017/05/flowers-love-profile-pictures-1.jpg'
const rocketChatClient = new RocketChatApi(
  'https',
  'rocket.chat',
  443,
  'username',
  'password',
  (err, result)=>{
    console.info('RC connected', result)
});
rocketChatClient.users.setAvatar(userId, avatarUrl, (err, body)=>{
});

在Node.js中运行此命令后,出现以下错误,有人可以帮助我吗?

\node_modules\rocketchat-api\lib\net.js:144
                    return callback ? callback(error, null) : reject(error);
                                      ^

TypeError: callback is not a function
    at Request.clientRequest [as _callback] (D:\node js projects\rocketTest\node_modules\rocketchat-api\lib\net.js:144:39)
    at self.callback (D:\node js projects\rocketTest\node_modules\request\request.js:185:22)
    at Request.emit (events.js:198:13)
    at ClientRequest.<anonymous> (D:\node js projects\rocketTest\node_modules\request\request.js:819:16)
    at Object.onceWrapper (events.js:286:20)
    at ClientRequest.emit (events.js:198:13)
    at TLSSocket.emitRequestTimeout (_http_client.js:662:40)
    at Object.onceWrapper (events.js:286:20)
    at TLSSocket.emit (events.js:198:13)
    at TLSSocket.Socket._onTimeout (net.js:442:8)
    at ontimeout (timers.js:436:11)
    at tryOnTimeout (timers.js:300:5)
    at listOnTimeout (timers.js:263:5)
    at Timer.processTimers (timers.js:223:10)

1 个答案:

答案 0 :(得分:0)

这是因为setAvatar()仅接受2个参数:avatarUrlcallback。如果传递3个参数,则第二个参数将为callback,如果不是函数则将其抛出TypeError(在您的示例中,第二个参数avatarUrl是字符串)。

请参考rocketchat-api source codelib/api/users.js的源代码:

setAvatar (avatarUrl, callback) {
    return this.client.request("POST", "users.setAvatar", {
        avatarUrl
    }, callback);
}

不幸的是,rocketchat-api模块的document不正确,这导致了问题。