NodeJS - WITHOUT EXPRESS - how to get query-params?
Asked Answered
P

5

6

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.

Punishable answered 3/12, 2018 at 15:1 Comment(4)
You need to parse the incoming request. Try something like body-parserRatliff
do I need explicit the body-parser ? or would it do url.parse(req.url) somehow , too? .. i mean, i get paramname=12345 when I do console.log(url.parse(req.url).query)Punishable
I'm checking, but your app.js should export the handleRequest function using module.exportsRatliff
oh, sorry, I have not copied it :) .. of course it exports the handleRequest as a module. so far it runs correctly until this one thing that i am not able to extract the query-varname or its value.Punishable
P
7

You can use the built-in querystring module:

const querystring = require('querystring');

...
const parsed = url.parse(req.url);
const query  = querystring.parse(parsed.query);
Periwig answered 3/12, 2018 at 15:32 Comment(0)
B
1

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

request path

Brachy answered 27/12, 2020 at 15:9 Comment(0)
M
1

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
Molehill answered 26/6, 2023 at 5:59 Comment(0)
F
0

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

Fick answered 17/11, 2022 at 9:49 Comment(0)
T
-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>'))
Taddeusz answered 27/10, 2023 at 10:30 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Perpetual

© 2022 - 2024 — McMap. All rights reserved.