Arschibald
Arschibald

Reputation: 127

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

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.

Upvotes: 6

Views: 6392

Answers (5)

Vitrag Shah
Vitrag Shah

Reputation: 1

Per newest Node documentation, original answer give to this question is deprecated now.

You need to use following code to parse parameters provided to GET request.

const parsedUrl = new URL(request.url, `http://${req.headers.host}`);
console.log(parsedUrl.searchParams.get('<parameter-name>'))

Upvotes: -1

Ronnie Smith
Ronnie Smith

Reputation: 18545

Node documentations shows how. You have to create a new URL object first then the methods like .searchParams.get('abc') are available.

const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// Prints 123

Upvotes: 1

Richard Ramos
Richard Ramos

Reputation: 59

well if you really want to manually to do this, first you must know that the http request object is a stream of data, so what we can do is collect that stream chunks of data at the end, then join all streams of data together and then convert that to a readable data

else if (url == "/register" && req.method == "POST"){

const chunks = [];
const dataObj = {};
req.on("data",(chunk)=>{
    chunks.push(chunk); //push the chunks of data to chunk array
});

req.on("end",()=>{

    let data = Buffer.concat(chunks); //join all the received chunk to a buffer data
    data = data.toString(); //convert the buffer data to a readable data
    const parseData = new URLSearchParams(data); //using the the URLSearchParams we can convert the result data to a separate pairs of values and data
    for (let pair of parseData.entries()){

        dataObj[pair[0]] = pair[1];
    }
    console.log(`your first name is : `,dataObj.first_name, `and your last name is :` ,dataObj.last_name)

})

res.write("<h1>form was submitted</h1>");
return res.end();}

enter image description here

Upvotes: 0

Jishan
Jishan

Reputation: 61

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

request path

Upvotes: 1

robertklep
robertklep

Reputation: 203231

You can use the built-in querystring module:

const querystring = require('querystring');

...
const parsed = url.parse(req.url);
const query  = querystring.parse(parsed.query);

Upvotes: 7

Related Questions