我是 Node JS 新手。我在我的第一个应用程序上遇到了这个问题。 Node 服务器正在运行。但在控制台中它说端口未定义,在浏览器上它说拒绝连接。
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req,res) =>{
res.statusCode = 200;
res.setHeader('Content-type','text/plain');
res.end('Hello world');
});
server.listen((port,hostname) => {
console.log('server started on port: '+port);
});
我已经尝试过http://127.0.0.1:3000/和 http://localhost:3000/ 。但没有成功。
最佳答案
调用listen
时不需要指定主机名。另外,端口应该是第一个参数,回调应该是第二个。
工作示例:
const http = require('http');
const port = 3000;
const server = http.createServer((req,res) =>{
res.statusCode = 200;
res.setHeader('Content-type','text/plain');
res.end('Hello world');
});
server.listen(port, (err) => {
// err handling
console.log('server started on port: '+port);
});
现在在浏览器上访问 localhost:3000
将产生您想要的结果。
关于node.js - Node 服务器正在运行,但无法在浏览器上运行且端口未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48734917/