【问题标题】:Url as req.params in Express网址作为 Express 中的 req.params
【发布时间】:2020-10-16 09:55:04
【问题描述】:

我想使用 express 和 mongo DB 根据 URL 查找文档。

我的架构包括

bandUrl: {
        type: String
    }

这是我在 Express 服务器中的 Rout。

// Get Single Band By bandUrl
router.get('/bandUrl/:url', (req, res) => {
    quoteGenerator.find({bandUrl: req.params.url}).then(gen => res.json(gen))
})

我将其中一个文档设置为将 bandUrl 设置为“http://localhost:3000/”。

我使用 URL 以外的其他东西测试了路由 - 只使用字符串就可以了……不过我真的很想使用 URL。有没有办法做到这一点?

这是我申请的假/测试路线..

const getFakeInfo = async () => {
    try {
        const response = await fetch(`/api/autoquotegenerators/bandUrl/http://localhost:3000/"`, {
            method: 'GET',
        })
        const responseData = await response.json()

        console.log(responseData)

    } catch (error) {
        console.log(error)
    }
}

我认为 URL 中多余的斜杠是导致问题的原因。

感谢您的帮助!

【问题讨论】:

    标签: mongodb express routes url-parameters


    【解决方案1】:

    您想要使用的是encodeURIComponent()。此函数转义所有 URI 特定字符,因此它们得到正确解释。您的请求代码应如下所示:

    const response = await fetch(`/api/autoquotegenerators/bandUrl/${encodeURIComponent("http://localhost:3000/")}`, {
        method: 'GET',
    })
    

    如果您想了解更多关于此功能的信息,可以查看here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 2015-03-26
      • 2020-07-13
      • 2018-07-10
      相关资源
      最近更新 更多