Hello World HTTP 服务器
首先,为你的平台安装 Node.js.
在这个例子中,我们将创建一个侦听端口 1337 的 HTTP 服务器,它将 Hello, World!
发送到浏览器。请注意,你可以使用当前未被任何其他服务使用的任何你选择的端口号,而不是使用端口 1337。
http
模块是 Node.js 核心模块 (Node.js 源中包含的模块,不需要安装其他资源)。http
模块提供使用 http.createServer()
方法创建 HTTP 服务器的功能。要创建应用程序,请创建包含以下 JavaScript 代码的文件。
const http = require('http'); // Loads the http module
http.createServer((request, response) => {
// 1. Tell the browser everything is OK (Status code 200), and the data is in plain text
response.writeHead(200, {
'Content-Type': 'text/plain'
});
// 2. Write the announced text to the body of the page
response.write('Hello, World!\n');
// 3. Tell the server that all of the response headers and body have been sent
response.end();
}).listen(1337); // 4. Tells the server what port to be on
使用任何文件名保存文件。在这种情况下,如果我们将其命名为 hello.js
,我们可以通过转到文件所在的目录并使用以下命令来运行应用程序:
node hello.js
然后可以使用 URL http:// localhost:1337 或 http://127.0.0.1:1337 在浏览器中访问创建的服务器。
将出现一个简单的网页,顶部显示 Hello World!
文本,如下面的屏幕截图所示。