简体   繁体   English

Express.Route如何确定路线

[英]How express.route determined route

I'm start learning about Node.js (with Express.js) and React.js. 我开始学习Node.js(带有Express.js)和React.js。 So I have some question about Express Router 所以我对快速路由器有些疑问

Let's see my part of code 让我们看看我的部分代码

server.js server.js

const app = express();
const apiRouter = require("./Routes/apiRoute");

app.use("/api", apiRouter);

app.listen(3000, () => {
  console.log("application run on port " + 3000);
});

/Routes/apiRoute.js /Routes/apiRoute.js

const express = require("express");
const router = express.Router();

router.route("/user/:id")
    .post((req,res)=>{
        // Do something
    })



router.route("/user/status")
    .post((req,res) => {
        // do something
    });

So. 所以。 My question is How express route determined which method to go. 我的问题是快递路线如何确定要使用的方法。

From my example code if I send POST request like this http://localhost:3000/api/user/status 从我的示例代码中,如果我发送POST请求,例如http://localhost:3000/api/user/status

express router will see status is :id right ? 快递路由器会看到状态是:id对吗?

in the otherhand if I move route for /user/status up it's will go as I expected right ? 另一方面,如果我将/user/status路由上移,它将按我的预期进行,对吗?

Thank you. 谢谢。

Express matches route in chronological order. Express按时间顺序匹配路线。

Express starts to match URL with the first route that has been declared in the script and then moves to the next if it does not match. Express开始将URL与脚本中已声明的第一个路由进行匹配,如果不匹配,则移至下一个。 This is because of the fact that Express is a Javascript framework. 这是因为Express是Javascript框架。 The function you pass to a route ie (req, res) => {...} is actually a js callback function that would be called if the user hit the route matching the corresponding string declared. 传递给路由的函数,即(req, res) => {...}实际上是一个js回调函数,如果用户点击与声明的相应字符串匹配的路由,则将调用该回调函数。 And in Javascript, the callback that is set first for an event is called first because these callbacks are maintained in a queue. 在Javascript中,首先为事件设置的回调被称为第一个,因为这些回调都保存在队列中。 A queue is FIFO as we all know. 众所周知,队列是FIFO。

If you want both "/user/:id" and "/user/status" to work, you would have to declare the later one first in your code and then the first one. 如果要同时使用"/user/:id""/user/status" ,则必须先在代码中声明后一个,然后再声明第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM