[javascript] How to get a URL parameter in Express?

I am facing an issue on getting the value of tagid from my URL: localhost:8888/p?tagid=1234.

Help me out to correct my controller code. I am not able to get the tagid value.

My code is as follows:

app.js:

var express = require('express'),
  http = require('http'),
  path = require('path');
var app = express();
var controller = require('./controller')({
  app: app
});

// all environments
app.configure(function() {
  app.set('port', process.env.PORT || 8888);
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
  app.set('view engine', 'jade');
  app.set('views', __dirname + '/views');
  app.use(app.router);
  app.get('/', function(req, res) {
    res.render('index');
  });
});
http.createServer(app).listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

Controller/index.js:

function controller(params) {
  var app = params.app;
  //var query_string = request.query.query_string;

  app.get('/p?tagId=/', function(request, response) {
    // userId is a parameter in the url request
    response.writeHead(200); // return 200 HTTP OK status
    response.end('You are looking for tagId' + request.route.query.tagId);
  });
}

module.exports = controller;

routes/index.js:

require('./controllers');
/*
 * GET home page.
 */

exports.index = function(req, res) {
  res.render('index', {
    title: 'Express'
  });
};

The answer is


If you want to grab the query parameter value in the URL, follow below code pieces

//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid

If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;

next();
});

// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});

You can do something like req.param('tagId')


This will work if your route looks like this: localhost:8888/p?tagid=1234

var tagId = req.query.tagid;
console.log(tagId); // outputs: 1234
console.log(req.query.tagid); // outputs: 1234

Otherwise use the following code if your route looks like this: localhost:8888/p/1234

var tagId = req.params.tagid;
console.log(tagId); // outputs: 1234
console.log(req.params.tagid); // outputs: 1234

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to url-parameters

What is the difference between URL parameters and query strings? RestTemplate: How to send URL and query parameters together How can I get query parameters from a URL in Vue.js? How can I get the named parameters from a URL using Flask? How to get a URL parameter in Express? PHP check if url parameter exists Pass Hidden parameters using response.sendRedirect() How to convert URL parameters to a JavaScript object? How to replace url parameter with javascript/jquery? Username and password in https url

Examples related to query-parameters

Angular: How to update queryParams without changing route RestTemplate: How to send URL and query parameters together How to get a URL parameter in Express? Escaping ampersand in URL How do I pass a URL with multiple parameters into a URL?