prasoonraj
prasoonraj

Reputation: 90

How to pass a "?" as a routing parameter in express while using node js

I am creating a blog website for my college using express and nodejs this might be a silly question but I need an answer. as you can see from the following piece of code-

enter code here
cons express = require("express");
.....
.....
app.get("/blog/:title_of_blog", function(request, response){ 
    var title_requested = request.params.title_of_blog;
    console.log(title_requested);
})

It works fine in all the cases I tried except when if a user enters a string in as a routing parameter like "what is your name?" then it console logs only "what is your name"

So a question mark gets excluded here on which further process depends as it should be exactly the same,

Is there any way I could fix this???

If you do need any additional information please do let me know

Upvotes: 1

Views: 60

Answers (3)

prasoonraj
prasoonraj

Reputation: 90

certain Characters such as ?, @ are not allowed in URL Parsing or I recently discovered even while storing cookies, but there is a simple way to avoid these problems and get your string in the desired way

var encodedString = encodeURI(rawString);

this above line turns all the characters such as @ into an easily parsable string and after the string is processed whenever you need the actual string you just have to type one line to get the original string

var originalString = decodeURI(enodedString);

Upvotes: 0

Zia ur Rehman
Zia ur Rehman

Reputation: 565

In JavaScript, PHP, and ASP there are functions that can be used to URL encode a string.

PHP has the rawurlencode() function, and ASP has the Server.URLEncode() function.

In JavaScript you can use the encodeURIComponent() function.

source

When you apply encoding on your blog title and pass URL Become like this

/blog/what%20is%20your%20name%20%3F

You will got the exact result as you want. :)

Upvotes: 0

Hoàng Trung
Hoàng Trung

Reputation: 46

Because express will understand ? is for starting a query string. So usually if you want to put blog title to URL, you can parse title to slug using some lib.

Upvotes: 1

Related Questions