I am trying to complete a simple project in the freeCodeCamp “API and Microservices” curriculum.
The project is rather simple, it requires working with Express.js, some routes are provided and others must be dynamically generated. In this case, either a string or number that can be parsed as
new Date() object. e.g.:
This last one got me stuck and makes the response fail every time. As a matter of fact, it gets accepted as valid in the Date() object. However, the resulting date is wrong because Express.js apparently parses or passes parameters rid of special characters.
05%20October%202011 gets logged out as
05 October 2011.
I have looked in the Express.js documentation and elsewhere on MDN, etc.
Apparently, I have found several ways to do this with the
query object, but not with the
I have also tried to provide middlewares that could mitigate the problem, but the issue arises from the Express API itself, and providing URL parsing middlewares would not be useful because not all requests are sent with special characters.
Does anyone know how to prevent Express.js to get rid of special characters and pass the URL parameters as they are?
Remember that the routes are casually checked by FFC server, hence it is not possible to act on the input itself.
Thank you very much.
I think you’re misunderstanding the task 🙂
Anything you type into a URL in a modern browser will be passed through
encodeURIComponent. For example, if you go to
https://httpbin.org/get?data=one two three, the browser will issue a request like
GET /get?data=one%20two%20three HTTP/2 (note that browsers may auto-convert
%20 to space for you when you inspect the request headers, in Firefox you can use the Raw switch on Headers tab).
The reason this is done is so that you can send text like
this&is=not&a=param as parameters without them being parsed as paths or query parameters.
Conventiently, express will auto-decode this for you, so that you see that
req.params.data = 'one two three'. There is no reason to fight this behaviour. Now, if you REALLY wanted to get your percents back, you could encode the parameter back using
const encoded = encodeURIComponent(req.params.data); console.log(encoded); // 'one%20two%20three'
For your example, what’s probably intended is that express automatically decodes
05 October 2011, which you can then use like
If you instead send
05%2520October%25202011 to the server, it will get decoded into
05%20October%202011. It looks like Node will get the first number as the day, the first word as the month, and the first four digits after the month as the year, which for
October%202011 leads to the year 2020.
If something is still unclear, please add more context or ask away 🙂