如何在 nodejs 中创建一个返回 Hello World 的简单服务器
封面图
•
2025-12-15
•
nodejs
231
0
0
0
在 Node.js 中创建一个返回 "Hello World" 的简单服务器,可以使用内置的 `http` 模块。下面是一个简单的示例代码: ### 步骤 1:创建一个新的 JavaScript 文件 比如,你可以创建一个名为 `server.js` 的文件。 ### 步骤 2:编写代码 将以下代码粘贴到 `server.js` 文件中: ```javascript // 引入 http 模块 const http = require('http'); // 创建 HTTP 服务器 const server = http.createServer((req, res) => { // 设置响应头(可选) res.writeHead(200, { 'Content-Type': 'text/plain' }); // 发送响应内容 res.end('Hello World\n'); }); // 监听端口(例如 3000) const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running at http://localhost:${PORT}`); }); ``` ### 步骤 3:运行服务器 在终端中运行以下命令来启动服务器: ```bash node server.js ``` ### 步骤 4:访问服务器 打开浏览器,访问以下地址: ``` http://localhost:3000 ``` 你应该会看到页面上显示: ``` Hello World ``` --- ### 可选:使用 Express 简化开发 如果你想要更简洁的方式,可以使用 [Express](https://expressjs.com/) 框架。以下是使用 Express 的版本: ```bash npm install express ``` 然后创建 `server.js`: ```javascript const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World'); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server is running at http://localhost:${PORT}`); }); ``` 运行: ```bash node server.js ``` 同样访问 `http://localhost:3000` 即可看到 "Hello World"。 --- 如果你有任何问题或需要进一步扩展功能,请随时告诉我!
上一篇:
我们如何在nodejs中使用async await ?
下一篇:
nodejs 如何工作的 ?
标题录入,一次不能超过6条
留言
评论