您的浏览器过于古老 & 陈旧。为了更好的访问体验, 请 升级你的浏览器
一位不愿透露姓名的用户 发布于2019年07月20日 14:32 最近更新于 2019年07月26日 13:11

Node.js express 如何监听 IPv4 地址

6244 次浏览 读完需要≈ 1 分钟 Node.jsExpressJavaScript

我是一个 Node.js 的入门新手,使用 Node.js + express 写了一个简单的 Hello World 程序。

不过我启动之后,却发现无法使用 IPv4 进行访问,只能使用 IPv6的地址 进行访问。

我的代码如下,大家帮我看看是怎么回事?

const express = require('express');

const app = express();

app.get('/', function (req, res) {
	res.send('Hello World');
});

app.listen(3000);

1 个回答

Ready · 4年前

根据express官方文档app.listen()函数的文档说明,它完全等同于 Node.js 的server.listen()

该函数的官方文档中对参数host描述如下:

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using server.address().port after the 'listening' event has been emitted.

If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.

In most operating systems, listening to the unspecified IPv6 address (::) may cause the net.Server to also listen on the unspecified IPv4 address (0.0.0.0).

什么意思呢?大致的意思就是:

如果 port 被省略或为 0, 操作系统会自动分配一个任意的未被使用的端口号;你可以在'listening'事件被触发后,通过使用 server.address().port 来获取到该端口号.

当参数 host 被省略时, 如果服务器的IPv6地址是可用的,那么服务器将使用本机所有的IPv6地址 (::)来接受连接;否则,将使用本机所有的IPv4地址(0.0.0.0)来接受连接。

在大多数操作系统上,监听本机所有的IPv6地址 (::) 可能导致net.Server 也监听本机所有的IPv4地址(0.0.0.0).

根据文档描述,如果你明确地只想使用(监听)IPv4地址。

那么你可以将最后一行代码改为:

app.listen(3000, '0.0.0.0');
已采纳 ? 0 0 0 编辑

撰写答案