2016-02-06 28 views
0
的NodeJS

我开始学习和的NodeJS当我实现了第一个剧本,我得到以下错误:类型错误:http.listen不是一个函数:

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._compile (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 

相应的脚本如下:

'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')); 

节点的版本是4.2.4

回答

0

listen不是http功能,但服务器的方法,你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')); 
0

当你写: -

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

http.createServer()返回称为服务器的对象。该Server对象具有可用的侦听方法。你正试图从http本身访问这个listen方法。这就是它显示错误的原因。

,所以你可以把它写,如: -

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') 
}); 

现在,它会让你的服务器的端口上侦听3000

相关问题