admin管理员组

文章数量:1312782

I was starting to learn NodeJS and when I implemented the first script, I get the following error:

http.listen(3000,() => console.log('Server running on port 3000'));
     ^

TypeError: http.listen is not a function
    at Object.<anonymous> (C:\Users\I322764\Documents\Node\HelloNode.js:11:6)
    at Module._pile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
    at node.js:963:3

The corresponding script is as follows:

'use strict';
const http = require('http');

http.createServer(
(req, res) => {
    res.writeHead(200, {'Content-type':'text/html'});
    res.end('<h1>Hello NodeJS</h1>');
}
);

http.listen(3000,() => console.log('Server running on port 3000'));

The version of node is 4.2.4

I was starting to learn NodeJS and when I implemented the first script, I get the following error:

http.listen(3000,() => console.log('Server running on port 3000'));
     ^

TypeError: http.listen is not a function
    at Object.<anonymous> (C:\Users\I322764\Documents\Node\HelloNode.js:11:6)
    at Module._pile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:313:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
    at node.js:963:3

The corresponding script is as follows:

'use strict';
const http = require('http');

http.createServer(
(req, res) => {
    res.writeHead(200, {'Content-type':'text/html'});
    res.end('<h1>Hello NodeJS</h1>');
}
);

http.listen(3000,() => console.log('Server running on port 3000'));

The version of node is 4.2.4

Share Improve this question asked Feb 6, 2016 at 14:38 Subham SoniSubham Soni 211 gold badge1 silver badge2 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

When you write:-

 http.createServer(function(req,res){
    res.writeHead(200);
    res.end("Hello world");
});
http.listen(3000);

http.createServer() returns an object called Server. That Server object has listen method available. And you are trying to access that listen method from the http itself. That's why it shows that error.

so you can write it like:-

var server=http.createServer(function(req,res){
        res.writeHead(200);
        res.end("Hello world");
    });
server.listen(3000,function(){
console.log('Server running on port 3000')
});

Now it will let your server listen on the port 3000.

listen isn't a function of http, but a method of the server you create with createServer:

var server = http.createServer((req, res) => {
    res.writeHead(200, {'Content-type':'text/html'});
    res.end('<h1>Hello NodeJS</h1>');
});

server.listen(3000,() => console.log('Server running on port 3000'));

本文标签: javascriptTypeError httplisten is not a function NodeJSStack Overflow