I am programming the backend of my web application. And I'm doing the api and I need to be able to send data in the URLs. For example:
www.example.com/posts/123456789
Right now all I have is:
www.example.com/posts/?q=123456789
I would like to know if I could do something similar to what the express module does with the colon to declare params. But I want to do it with the node http module as I have already written all the routing with it and it would be a huge pain to move to express and have to memorize the functions for it.
if this isn't possible please let me know and I will have to stick to the query string.
CodePudding user response:
If I understand your question correctly you would do something like this.
I will give you whole server code, just pass it and run it.To see it for yourself
What this code does is for example -> localhost:8080/month?9 when you pass this into the browser the console will print out the 9
const http = require('http');
const url = require('url');
http.createServer(function (req, res) {
const queryObject = url.parse(req.url,true).query; <---- Here is where you "catch" the URI parameters
console.log(queryObject); <-- here you display them
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Feel free to add query parameters to the end of the url');
}).listen(8080);
CodePudding user response:
Seems like HTTP module docs do not specify a way to do this, other than by using search params.
In your case however, I think that the best course of action (if migrating to a framework like express is not an option) would be to manually deconstruct the URL with using something like:
const urlSegments = request.url.split('/')
and taking n-th segment (matching the route you specified).
This is a bad solution in the long term, as it would be quite difficult to maintain, but it can get the job done if necessary.