当我尝试重定向到已解码的 url 时,它会将我重定向到我的 url.com/myurl 而不是将我带到页面

when i try to redirect to decoded url it will redirect me to my myurl.com/myurl instead taking me to the page

我正在制作 link 起酥油。我以前遇到 URLs 的问题,但它在将 URL 放入数据库时​​通过编码得到修复,并且在重定向时它将解码 URL 并重定向到它。问题是,它没有将我重定向到 like https://google.com,而是将我重定向到 mypage.com/google.com。当它只是解码 URL 并且 URL 正常时,我尝试制作一个“调试”页面,使用 HTTPS:// 和所有内容。最大的问题是它都在 localhost 上工作,但是当我将它部署到我的 VPS 上时它不工作。只有解码 URL 的调试页面有效。我正在使用 express.js 和猫鼬。这是我重定向用户的代码:

    app.get('/:shortUrl', async (req, res) => {
         const shortUrl = await shorturl.findOne({ short: req.params.shortUrl })
    if (shortUrl == null) {
        res.send('URL not found!')
    } else {
        shortUrl.clicks++
        shortUrl.save()
        res.redirect(decodeURIComponent(shortUrl.full))
    }
})

如果 URL 没有方案,在浏览器中它假定方案是 HTTP,但在 HTTP 重定向中域看起来像带点的路径。如果您重定向到一个路径,它将重定向到同一个域,这解释了 google.com.

的行为

尝试规范化 URL 或验证完整的 URL 包含方案。

https://github.com/sindresorhus/normalize-url

https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL

您可以使用内置的 URL 对象来确保重定向 URL 完整且有效:

res.redirect(new URL(decodeURIComponent(shortUrl.full)).toString())

如果无法从输入中生成有效的 URL,它将抛出,因此最好将其包装在 try/catch.

try {
  res.redirect(new URL(decodeURIComponent(shortUrl.full)).toString());
} catch (e) {
  res.send('Invalid URL');
}