Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - WITHOUT EXPRESS - how to get query-params?

Tags:

node.js

req

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.

like image 749
Arschibald Avatar asked Mar 05 '23 23:03

Arschibald


2 Answers

You can use the built-in querystring module:

const querystring = require('querystring');

...
const parsed = url.parse(req.url);
const query  = querystring.parse(parsed.query);
like image 167
robertklep Avatar answered Mar 19 '23 02:03

robertklep


you can use 'url' moduele for getting query params in pure Nodejs (without express) below are some code snippets- code snippet

request path

like image 32
Jishan Avatar answered Mar 19 '23 01:03

Jishan