How to get GET (query string) variables in Node.js

2 Answers

0 votes
var url = require('url');

const myURL = 'https://www.website.com/orders/index.html?id=8372&age=43';
 
var url_parts = url.parse(myURL, true);

var query = url_parts.query;

console.log(query.id);
console.log(query.age);

 
    
/*
run:
  
8372
43
  
*/

 



answered Mar 22, 2020 by avibootz
0 votes
var url = require('url');
const http = require('http');
  
const PORT = process.env.PORT || 8080;

http.createServer((req, res) => {
    const queryObject = url.parse(req.url,true).query;
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(queryObject.age + ' ' + queryObject.name);
}).listen(PORT, () => console.log(`Server started on port ${PORT}`)); 


    
/*
run:
  
Server started on port 8080

On http://localhost:8080/?age=48&name=Tom
48 Tom

*/

 



answered Mar 22, 2020 by avibootz

Related questions

3 answers 274 views
1 answer 218 views
3 answers 377 views
1 answer 148 views
3 answers 257 views
2 answers 224 views
224 views asked Feb 27, 2020 by avibootz
...