获得" TypeError:"听众"参数必须是一个函数"在Node.Js中

时间:2017-08-31 10:29:23

标签: node.js

app.js

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

http.createServer(200, function(req, res){
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data){
    if(err)
    {
        res.writeHead(404, {'Content-Type' : 'text/html'});
        return res.end("404 Not Found!!!");
    }
    res.writeHead(200, {'Content-Type' : 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

当我尝试使用命令" node app.js"运行它时,我收到以下错误:

events.js:238
    throw new TypeError('"listener" argument must be a function');
    ^

TypeError: "listener" argument must be a function
    at _addListener (events.js:238:11)
    at Server.addListener (events.js:298:10)
    at new Server (_http_server.js:263:10)
    at Object.createServer (http.js:35:10)
    at Object.<anonymous> (E:\AngularJS\New folder\app2.js:7:6)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)

我试图找出解决方案,但无法解决问题。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

只需删除200, 检查以下代码

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

http.createServer(function(req, res){
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data){
    if(err)
    {
        res.writeHead(404, {'Content-Type' : 'text/html'});
        return res.end("404 Not Found!!!");
    }
    res.writeHead(200, {'Content-Type' : 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

答案 1 :(得分:0)

http.createServer只需要function,其中包含2个回调项(response, request)。只需从createServer调用中删除200或将其替换为:

http.createServer(function(req, res) { ... }

您可以在此处详细了解:https://nodejs.org/api/http.html#http_http_createserver_requestlistener