¿Cómo obtener un parámetro de URL en Express?


Me enfrento a un problema al obtener el valor de tagid de mi URL: localhost:8888/p?tagid=1234.

Ayúdame a corregir el código de mi controlador. No puedo obtener el valor tagid.

Mi código es el siguiente:

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'
  });
};
Author: Xufox, 2013-11-20

4 answers

Express 4.x

Para obtener el valor de un parámetro URL, use req.parámetros

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.params.tagId);
});

// GET /p/5
// tagId is set to 5

Si desea obtener un parámetro de consulta ?tagId=5, utilice req.query

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query.tagId);
});

// GET /p?tagId=5
// tagId is set to 5

Express 3.x

Parámetro de URL

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.param("tagId"));
});

// GET /p/5
// tagId is set to 5

Parámetro de consulta

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query("tagId"));
});

// GET /p?tagId=5
// tagId is set to 5
 482
Author: maček,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-16 20:11:41

, puedes hacer algo como req.param('tagId')

 16
Author: tomahim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-20 07:12:30

Si desea obtener el valor del parámetro de consulta en la URL, siga las siguientes piezas de código

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

Si desea obtener el parámetro URL utilizando la función Express param

Función Express param para capturar un parámetro específico. Esto se considera middleware y se ejecutará antes de que se llame a la ruta.

Esto se puede usar para validaciones o para obtener información importante sobre item.

Un ejemplo para esto sería:

// 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+ '!');
});
 4
Author: Malatesh Patil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-06 12:38:53

Esto funcionará si su ruta es como: localhost: 8888 / p?tagid = 1234

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

Esto funcionará si tu ruta es como:localhost: 8888/p/: tagid=1234

var tagId = req.params.tagid;
console.log(tagId); //1234
console.log(req.params.tagid); //1234
 1
Author: ajay saini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-18 11:18:30