I call my app by localhost:3000?paramname=12345
inside NodeJS I have
server.js
var http = require('http');
var app = require('./app');
var server = http.createServer(app.handleRequest).listen(3000, function () {
console.log('Server running on Port 3000');
});
and my app.js
var url = require('url');
var path = require('path');
function handleRequest(req, res) {
// parse url and extract URL path
var pathname = url.parse(req.url).pathname;
// file extention from url
const ext = path.extname(pathname);
console.log(req.url);
});
now the console.log(req.url)
would output me /?paramname=12345
but how would i get only the var-name paramname
or it's value 12345
??
when I try everything i find, but I onl get undefined
or the script brakes because no such function.
You can use the built-in querystring
module:
const querystring = require('querystring');
...
const parsed = url.parse(req.url);
const query = querystring.parse(parsed.query);
you can use 'url' moduele for getting query params in pure Nodejs (without express)
below are some code snippets-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With