事件起因:开始看《Node.js实战(第2版)》,对着代码清单1-2敲击一番。十几行的代码,我这种菜鸟也能看个大概。谁知天意弄人,代码敲完了, 存盘hello.js,期待的那一刻没出现。哎?
代码如下:
const http=require('http');
const hostname='127.0.0.1';
const port=8080;
const server=http.createServer((req,res)=>{
res.end('hello world.');
});
server.listen(port,hostname,()=>{
console.log('server listening on:http://localhost:%s',port);
});
怎么回事?
node hello.js
当我运行时,奇迹发生了。这么简单的代码,还报错?!!!是我敲错了吗?
F:\mywebsite>node hello.js
events.js:292
throw er; // Unhandled 'error' event
^
Error: listen EACCES: permission denied 127.0.0.1:8080
at Server.setupListenHandle [as _listen2] (net.js:1301:21)
at listenInCluster (net.js:1366:12)
at doListen (net.js:1503:7)
at processTicksAndRejections (internal/process/task_queues.js:81:21)
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1345:8)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
code: 'EACCES',
errno: -4092,
syscall: 'listen',
address: '127.0.0.1',
port: 8080
}
赶紧跑到官网上去查实例。官网的实例代码与我这个略有出入。但总体不差。代码如下:
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!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
把这段直接copy下来。在vs code中运行。一切正常啊。localhost:3000,分毫不错。是的,我仔仔细细地对比了一下。为此还学会了vs code中两个文件的对比方法。(呵呵,中年大叔学前端也不怕人笑话)
反复几次之后。问题找到了,我把错误代码中的port号也换成3000时,一切都正常了。
事后总结
接下来的事情就简单了,首先明白了。原来是8080端口被占用了。
- 查是否被占用,可以在命令窗口用 netstat -ano检查一下。
- 其实最开始给出的报错中有errno:-4092,4092就是端口被占用错误。