Node学习中“Hello world”遇坑记

事件起因:开始看《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端口被占用了。

  1. 查是否被占用,可以在命令窗口用 netstat -ano检查一下。
  2. 其实最开始给出的报错中有errno:-4092,4092就是端口被占用错误。

记录一下,也许也象我这样初学前端的人有用吧。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容