如何使用路由参数和查询参数在Express中创建API

时间:2020-04-08 10:22:11

标签: node.js express routes routeparams

我的应用程序在带有express的nodejs中。

我正在尝试构建同时具有路由参数和查询参数的API

下面是我尝试过的事情

 using **=**

 app.get('/:accountId/accounts/password/update?uniqueCode={uniqueCode}', async function(req, res) {
         //my code here
    }

app.get('/:accountId/accounts/password/update?uniqueCode/:uniqueCode', async function(req, res) {
             //my code here
   }

但是当我像下面这样从邮递员那里碰到这个

http://localhost:5000/722/account/password/update?uniqueCode={dfgsfksjfksdhfksj}

我尝试的两种方式都从express中收到NOTFOUND错误。谁能建议我该怎么做。

1 个答案:

答案 0 :(得分:1)

您必须检查代码中的queryParams:

app.get('/:accountId/accounts/password/update', async function(req, res, next) {
          const accountId = req.params.accoundId;
          const  uniqueCode = req.query.uniqueCode;
         ...
          if (/* checkuniqueCode is not valid */) {
               return next()
           }

 }

这是文档:https://expressjs.com/fr/api.html#req.query