如何在express节点js中获取url参数
我面临着从我的url获取tagid价值的问题。 本地主机:8888 / P标签识别= 1234
帮助我纠正我的控制器代码。 我无法获得tagid值。
我的代码如下:
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')); });
控制器/ 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;
路线/ index.js
require('./controllers'); /* * GET home page. */ exports.index = function(req, res){ res.render('index', { title: 'Express' }); };
Express 4.x
要获取URL参数的值,请使用req.params
app.get('/p/:tagId', function(req, res) { res.send("tagId is set to " + req.params.tagId); }); // GET /p/5 // tagId is set to 5
如果你想得到一个查询参数?tagId=5
,那么使用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
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
查询参数
app.get('/p', function(req, res) { res.send("tagId is set to " + req.query("tagId")); }); // GET /p?tagId=5 // tagId is set to 5
你可以做一些像req.param('tagId')
如果您想抓取URL中的查询参数值,请按照以下代码片段进行操作
//url.localhost:8888/p?tagid=1234 req.query.tagid OR req.param.tagid
如果您想使用Express param函数获取URL参数
Express param函数来获取一个特定的参数。 这被认为是中间件,将在路由被调用之前运行。
这可以用于validation或获取有关项目的重要信息。
一个例子是:
// 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+ '!'); });