我試圖按標題查找和檢索帖子,但失敗了,當我控制臺日志requestedTitle = req.params.postTitle顯示?從 http://localhost:1035/posts/Is Google Analytics is illegal 中洗掉?只是“谷歌分析是非法的”,它沒有找到標題為“谷歌分析是非法的嗎?”的文章。帶一個?。
app.get('/posts/:postTitle', function (req, res) {
//single blog post
// const postId = req.params.postId
const requestedTitle = req.params.postTitle
Post.findOne({title: requestedTitle}, function (err, post) {
console.log(requestedTitle);
if (post) {res.render('post', {
singleTitle: post.title,
singleContent: post.content,
singleAuthor: post.author,
uploadedImg: post.img,
postCreated: post.created_at
})} else {
res.send(`No "${requestedTitle}" article was found.`)
}
uj5u.com熱心網友回復:
問號被 Express(并且根據 http 規范)解釋為 URL 查詢字串的分隔符。因此,Express 已經決議出查詢字串,并且與您的路線不匹配。決議的查詢字串將在req.query.
因此,如果您發送對 URL 的請求,例如:
http://localhost:1035/posts/Is Google Analytics is illegal?
然后,?將被視為查詢字串的分隔符,而您的 postTitle 將只是Is Google Analytics is illegal.
如果您希望問號成為您獲取的內容的一部分postTitle,那么客戶端必須在構造 URL 之前正確編碼postTitleusing 。encodeURIComponent()這將“隱藏”?來自 Express (它將被編碼為?,然后將其保留在 as 的解碼值postTitle中?。
僅供參考,還有許多其他字符也被保留,因此您嘗試放入 URL 片段中的任何最終用戶內容都postTitle必須encodeURIComponent()在構建 URL 時進行編碼。請注意,您不會呼叫encodeURIComponent()整個 URL,而只是呼叫成為 postTitle 的用戶資料。Express 將為您處理解碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/425899.html
