gpt4 book ai didi

javascript - 如何访问node.js模块中的查询参数?

转载 作者:行者123 更新时间:2023-12-03 08:21:47 25 4
gpt4 key购买 nike

我为我的 Express 应用程序编写了简单的分页模块。这是代码:

var config = require('../config');

function Pagination(options) {
this.param = options.param || 'page';
//this.current = ?
this.perPage = options.perPage || config.perPage;
this.numPages = Math.ceil(options.numRows / this.perPage);
this.prevPage = null;
this.nextPage = null;
this.hasPrevPage = function() {
return (this.current > 1 && this.numPages);
}
this.hasNextPage = function() {
return (this.numPages > this.current);
}

if (this.hasPrevPage()) {
this.prevPage = this.current - 1;
}

if (this.hasNextPage()) {
this.nextPage = this.current + 1;
}
}

module.exports = Pagination;

选项属性之一是param。 get请求参数的名称,默认为“page”。例如当路线是:

/posts/?page=3

pagination.current 设置为 3

我认为在我的应用程序中使用此模块应该如下所示

app.js:

//...
var postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);

(/routes/posts.js):

var express       = require('express');
var Pagination = require('..core/pagination');
var config = require('../config');

var router = express.Router();

router.get('/', function(req, res) {
//...
pagination = new Pagination({
numRows: dbresult.count,
perPage: config.perPage
});

res.render('posts', {posts: dbresult.rows, pagination: pagination});
});

因此,如果模块知道分页参数的名称是什么,它应该能够获取它的值。如何在模块内部而不是在每个路由内部执行此操作?仅使用基本 Node 功能是可取的。

最佳答案

使用req.query.page获取3。换句话说,

router.get('/posts', function(req, res) {
var page = req.query.page // = 3

关于javascript - 如何访问node.js模块中的查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33717520/

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