学习 MERN Stack 第 35 天
今天我构建了我的第一个原生 Web 服务器。
在我的 Node.js 课程中,我不再局限于编写本地脚本。我的代码不再是运行后就停止。现在,服务器会保持活跃状态,监听来自互联网的连接。
我学习了计算机如何在网络上进行通信。以下是我的学习心得:
The http Module
我使用了原生的 http 工具来处理数据。我使用 http.createServer() 来启动服务器。该函数接受两个参数:
req:它保存来自浏览器的数据,例如 URL 或请求头 (headers)。res:它将数据发送回用户,例如 HTML 或 JSON。
The listen Method 服务器需要一个特定的端口来进行通信。我将服务器设置为监听 8000 端口。这充当了接收请求的网关。
代码实现:
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello from my Day 35 custom server!");
});
server.listen(8000, () => {
console.log("Server is live on port 8000");
});
来源:https://dev.to/ali_hamza_589ec7b3eb6688d/day-35-of-learning-mern-stack-ldn