学习 MERN Stack 第 38 天

我正处于 MERN stack 学习之旅的第 38 天。

昨天,我学习了如何从 URL 中提取查询字符串。今天,我学习了 HTTP 请求方法。

在今天之前,我的服务器对每个请求的处理方式都是一样的。现在,我可以根据用户的意图让后端执行不同的操作。这让一个静态端点转变为一个功能性工具。

我重点研究了 req.method 属性。这个属性告诉服务器客户端想要执行什么操作。

以下是我学到的四种主要方法:

当你使用 req.method 时,你就在控制应用程序的逻辑。你可以决定用户是在同一个 URL 下查看页面还是提交表单。

代码示例:

const http = require("http");

const server = http.createServer((req, res) => { if (req.url === "/api/data") { if (req.method === "GET") { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("Reading database records..."); } else if (req.method === "POST") { res.writeHead(201, { "Content-Type": "text/plain" }); res.end("Creating new data!"); } } else { res.end("Standard Route"); } }); server.listen(8000);

来源:https://dev.to/ali_hamza_589ec7b3eb6688d/day-38-of-learning-mern-stack-opl