学习 MERN Stack 第 36 天

我正在进行 MERN stack 学习之旅的第 36 天。昨天,我搭建了第一个本地 Web 服务器。今天,我专注于后端路由(routing)。

路由(Routing)根据 URL 告诉服务器应该显示哪些内容。你可以把后端想象成应用程序的交通控制器。

我学习了如何使用请求对象(request object)来管理路径。其工作原理如下:

以下是我练习的代码:

const server = http.createServer((req, res) => {
    if (req.url === "/") {
        res.end("Welcome to the Homepage!");
    } else if (req.url === "/about") {
        res.end("This is the About Page detailing our stack.");
    } else {
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("404: Page Not Found!");
    }
});

这种方法允许你为用户创建不同的端点(endpoints)。如果路径不存在,你会发送一个 404 错误。

来源:https://dev.to/ali_hamza_589ec7b3eb6688d/day-36-of-learning-mern-stack-183m