gpt4 book ai didi

javascript - 如何在 Express 中获取 URL 参数?

转载 作者:IT老高 更新时间:2023-10-28 13:12:29 28 4
gpt4 key购买 nike

我在从我的网址获取 tagid 的值时遇到问题:localhost:8888/p?tagid=1234

帮助我纠正我的 Controller 代码。我无法获取 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'));
});

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'
});
};

最佳答案

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

网址参数

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

关于javascript - 如何在 Express 中获取 URL 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20089582/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com