类型错误:回调不是 nodejs 中的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42218120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:00:29  来源:igfitidea点击:

TypeError: callback is not a function in nodejs

node.js

提问by

I am trying learn nodejs and stumble upon this error

我正在尝试学习 nodejs 并偶然发现此错误

TypeError: callback is not a function

类型错误:回调不是函数

when I am trying to call the server using this command.

当我尝试使用此命令调用服务器时。

curl http://localhost:8090/albums.json

curl http://localhost:8090/albums.json

and here is the code for my server.js

这是我的 server.js 的代码

var http = require('http'),
  fs = require('fs');

function load_album(album_name, callback) {
  fs.readdir("albums/", +album_name, (err, files) => {
    if (err) {
      if (err.code == "ENOENT") {
        callback(make_error("no_such_album", "That album doesn't exist"));
      } else {
        callback(make_error("can't load album", "The server is broken"));
      }
    } else {
      //callback(null, files);
      var only_files = [];
      var path = 'albums/${album_name}/';

      var iterator = (index) => {
        if (index == files.length) {
          var obj = {
            short_name: album_name,
            photos: only_files
          };
          callback(null, obj);
          return;
        }

        fs.stat(path + files[index], (err, stats) => {
          if (!err && stats.isFile()) {
            only_files.push(files[index]);
          }
          iterator(index + 1);
        });
      };
      iterator(0);
    }
  });
}


function handle_incoming_request(req, res) {
  console.log("incoming request: " + req.method + " " + req.url);

  if (req.url == '/albums.json') {
    load_album((err, albums) => {
      if (err) {
        res.writeHead(500, {
          "Content-Type": "application/json "
        });
        res.end(JSON.stringify({
          code: "cant_load_albums",
          message: err.message
        }));
      } else {
        var output = {
          error: null,
          data: {
            albums: albums
          }
        };
        res.writeHead(200, {
          "Content-Type": "application/json"
        });
        res.end(JSON.stringify(output) + "\n");
      }
    });
  } else if (req.url.substr(0, 7) == '/albums' && req.url.substr(req.url.length - 5) == '.json') {
    //user is requesting contents of album
    load_album(req.url.substr(7, req.url.length - 12), (err, photos) => {
      if (err) {
        res.writeHead(500, {
          "Content-type": "application/json"
        });
        res.end(JSON.stringify(err));
      } else {
        var output = {
          error: null,
          data: {
            photos: photos
          }
        };
        res.writeHead(200, {
          "Content-Type": application / json
        });
        res.end(JSON.stringify(output) + "\n");
      }
    });
  } else {
    res.writeHead(404, {
      "Content-type": "application/json"
    });
    res.end(JSON.stringify({
      code: "no_such_page",
      message: "No such page"
    }));
  }
}
var s = http.createServer(handle_incoming_request);
s.listen(8090);

can you tell me what's wrong with my code that I got an error telling me callback isn't a function?

你能告诉我我的代码有什么问题,我有一个错误告诉我回调不是一个函数吗?

thanks though

不过谢谢

for more formatted code then you can go here https://jsfiddle.net/02dbx6m9/

更多格式化代码,那么你可以去这里https://jsfiddle.net/02dbx6m9/

采纳答案by Vikas

var http = require('http'),
  fs = require('fs');

function load_album(album_name, callback) {
  fs.readdir("albums/", +album_name, (err, files) => {
    if (err) {
      if (err.code == "ENOENT") {
        callback(make_error("no_such_album", "That album doesn't exist"));
      } else {
        callback(make_error("can't load album", "The server is broken"));
      }
    } else {
      //callback(null, files);
      var only_files = [];
      var path = 'albums/${album_name}/';

      var iterator = (index) => {
        if (index == files.length) {
          var obj = {
            short_name: album_name,
            photos: only_files
          };
          callback(null, obj);
          return;
        }

        fs.stat(path + files[index], (err, stats) => {
          if (!err && stats.isFile()) {
            only_files.push(files[index]);
          }
          iterator(index + 1);
        });
      };
      iterator(0);
    }
  });
}


function handle_incoming_request(req, res) {
  console.log("incoming request: " + req.method + " " + req.url);

  if (req.url == '/albums.json') {
    load_album("ALBUM NAME", (err, albums) => {
      if (err) {
        res.writeHead(500, {
          "Content-Type": "application/json "
        });
        res.end(JSON.stringify({
          code: "cant_load_albums",
          message: err.message
        }));
      } else {
        var output = {
          error: null,
          data: {
            albums: albums
          }
        };
        res.writeHead(200, {
          "Content-Type": "application/json"
        });
        res.end(JSON.stringify(output) + "\n");
      }
    });
  } else if (req.url.substr(0, 7) == '/albums' && req.url.substr(req.url.length - 5) == '.json') {
    //user is requesting contents of album
    load_album("Album Name", req.url.substr(7, req.url.length - 12), (err, photos) => {
      if (err) {
        res.writeHead(500, {
          "Content-type": "application/json"
        });
        res.end(JSON.stringify(err));
      } else {
        var output = {
          error: null,
          data: {
            photos: photos
          }
        };
        res.writeHead(200, {
          "Content-Type": application / json
        });
        res.end(JSON.stringify(output) + "\n");
      }
    });
  } else {
    res.writeHead(404, {
      "Content-type": "application/json"
    });
    res.end(JSON.stringify({
      code: "no_such_page",
      message: "No such page"
    }));
  }
}
var s = http.createServer(handle_incoming_request);
s.listen(8090);

You forgot to pass album name parameter in load_album method. That's why album_name parameter is assigned the actual callback, while callback parameter remains undefined.

您忘记在 load_album 方法中传递专辑名称参数。这就是为什么为专辑名称参数分配了实际回调,而回调参数保持未定义的原因。

回答by Filip Dupanovi?

Here is the root cause of your issue:

这是您问题的根本原因:

load_album((err, albums) => {
    // ...
});

The signature for the function requires two parameters, yet you're only passing the first one:

该函数的签名需要两个参数,但您只传递第一个参数:

function load_album(album_name, callback) {}

Therein, once called, callbackwill be undefined, yet you're trying to treat it as a callable. Here's a more succint example of how to reproduce the error:

其中,一旦被调用,callback将是未定义的,但您试图将其视为可调用的。下面是如何重现错误的更简洁的示例:

function foo(bar, baz) {
  baz() 
}

foo(() => {})