我正在做一個鏈接縮短器。鏈接縮短器作業得很好,但現在我正在嘗試為它做 API。問題是,如果我在 get URL 中傳遞 URL 引數,它就不起作用。我嘗試了很多東西,但它不起作用。當我喜歡 http://localhost:3500/api/create/google.com 它可以作業但是當我做 http://localhost:3500/api/create/https://google.com 它不作業因為https://。這些是通過我的 API 失敗的最后 3 個輸入:http://https:google.com、google.com、http:// 我正在使用 express 和 mongoose。這是我的代碼:
app.get('/api/create/:shortUrl(*)', async (req, res, next) => {
if (req.params.shortUrl.includes("https://") || req.params.shortUrl.includes("http://") || req.params.shortUrl.includes("/")) {
req.params.shortUrl = req.params.shortUrl.replace("https://", "").replace("http://", "").replace("/", "")
}
if (req.params.shortUrl == "") {
res.send("invalid URL")
}
await shorturl.create({full: `http://${req.params.shortUrl}`})
const shortUrls = await shorturl.find().sort({_id: -1}).limit(-1)
const latest = shortUrls[0]
res.send("https://p33t.link/" latest.short)
});
uj5u.com熱心網友回復:
你必須包含受限制的字符,如URL的正確編碼部分:和//不屬于實際的協議,使之成為法律URL的一部分。因此,我們的想法是在將“引數”附加到 URL 之前對其進行編碼。據推測,您會使用encodeURIComponent(), 取決于您將其放置在 URL 中的確切位置。
在決議 URL 的核心部分后,Web 服務器將對 URL 的其余部分進行解碼,并回傳原始字符。我建議您的特定用途可能更適合作為查詢引數,而不是路徑的一部分,當正確編碼時,它會為您提供此資訊:
http://localhost:3500/api/create?u=https://google.com
然后,您可以使用:
app.get('/api/create', (req, res) => {
console.log(req.query.u);
...
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/398912.html
標籤:javascript 表达 猫鼬
上一篇:nodejsexpress重新連接mysqlER_ACCESS_DENIED_ERROR:用戶''@'localhost'訪問被拒絕(使用密碼:否)
