I tried to find and retrieve a post by a title but it failed and when I console log requestedTitle = req.params.postTitle
it shows the ? is removed from http://localhost:1035/posts/Is Google Analytics is illegal? to just "Is Google Analytics is illegal" which fails to find the article with the title "Is Google Analytics is illegal?" with a ?.
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.`)
}
CodePudding user response:
A question mark is interpreted by Express (and per the http spec) as the delimiter for the URL query string. As such, Express has already parsed out the query string and does not match that against your route. The parsed query string will be in req.query
.
So, if you send a request for a URL such as:
http://localhost:1035/posts/Is Google Analytics is illegal?
Then, the ?
will be seen as the delimiter for the query string and your postTitle will just be Is Google Analytics is illegal
.
If you want a question mark to be part of what you get in postTitle
, then the client will have to properly encode the postTitle
using encodeURIComponent()
before constructing the URL. That would "hide" the ?
from Express (it would be encoded as ?
and it would then be left in the decoded value of postTitle
as a ?
.
FYI, there are many other characters which are also reserved so ANY end-user content you're trying to put into the URL piece that you want to be postTitle
MUST be encoded with encodeURIComponent()
when constructing the URL. Note, you don't call encodeURIComponent()
on the entire URL, just on the piece of user data that becomes the postTitle. Express will then handle the decoding for you.