Kartik Garasia
Kartik Garasia

Reputation: 1454

How to get id from URL as variable? In Node.js

This is my express app running on Node.js

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('id: ' + req.query.id);
});

app.listen(3000);
console.log('working...');

//so i need url id as var
var gotID = req.query.id

//want to use this data to another js file
module.exports = gotID;

So I want that URL id as my variable.

Which is look like this URL

http://localhost:3000/[id that i want]

So what should I do?

I'm new to Node.js

Upvotes: 12

Views: 43256

Answers (1)

ruedamanuel
ruedamanuel

Reputation: 1930

This should work for you:

app.get('/:id', function(req, res) {
    res.send('id: ' + req.params.id);
});

req.query is used for search query parameters (i.e. everything after ? in http://something.com/path?foo=var)

Upvotes: 36

Related Questions