首页 > 解决方案 > 获取完整的路由 url expressJs

问题描述

我想在 express js 中获取路由的 URL。

http://localhost:9310/api/arsys/v1/entry/SimpleForm5/?fields=Request ID,Assigned To,Status,Submitter,Create Date&q=Status=New&offset=5&sort=Create Date.desc

我只想http://localhost:9310/api/arsys/v1/entry/SimpleForm5/

我试过const url = req.protocol + '://' + req.headers.host + req.url;http://localhost:9310/SimpleForm5/?fields=Request%20ID,Assigned%20To,Status,Submitter,Create%20Date&q=Status=New&offset=5&sort=Create%20Date.desc

但它不给/api/arsys/v1/entry/。我也不希望输出中的查询参数。

请帮忙

标签: node.jsexpress

解决方案


要检索没有 queryParams 的 url,但是使用主机 originalUrl,您可以这样:

const urlWithoutQueryParams = req.protocol + '://' + req.headers.host + url.parse(req.originalUrl).pathname;

例如,考虑该代码:

router.route('/arsys/v1/entry/SimpleForm5/')
  .get(async (req, res) => {
    try {
      console.log(req.protocol + '://' + req.headers.host + url.parse(req.originalUrl).pathname)
      return res.status(200).send({ message: "OK" });
    } catch (error) {
      return res.status(500).send({ message: "Failure" });
    }
  });

app.use('/api', router);

app.listen(8080, () => {
  log.info('app started')
})

当您发送GET至:

http://localhost:8080/api/arsys/v1/entry/SimpleForm5/?fields=Request ID,Assigned To,Status,Submitter,Create Date&q=Status=New&offset=5&sort=Create Date.desc

结果是:

http://localhost:8080/api/arsys/v1/entry/SimpleForm5/

推荐阅读