简体   繁体   English

发送json对象或使用快速路由渲染视图

[英]send json object or render a view with express route

I have two routes: /news and /news-paginate (I know it is a not good URL but it doesn't matter atm). 我有两条路线: /news/news-paginate (我知道这不是一个很好的URL,但是与atm无关)。 In the news route, I load 5 records from the database and render a populated view. news路线中,我从数据库中加载了5条记录,并呈现了一个填充视图。 In the /news-paginate route, I load other 5 records based on the page number and size sent from the client; /news-paginate路由中,我根据客户端发送的页码和大小加载其他5条记录; this route responds with a JSON object. 该路由以JSON对象作为响应。

news route 新闻路线

router.get('/news', function (req, res) {

...

  connection.query(queries['news_list'], [language, +pageSize, +offset], function (err, rows) {
      res.render('news', {news: rows});
  });
});

news-paginate route 新闻分页路线

router.get('/news-paginate', function (req, res) {
  var language = 'RU';
  var pageSize = req.query.pageSize;
  var pageNumber = req.query.pageNumber;
  var offset = (pageNumber - 1) * pageSize;

  connection.query(queries['news_list'], [language, +pageSize, +offset], function (err, rows) {
    res.json(rows);
  });
});

I am concerned about my architecture. 我担心自己的架构。 Is my approach correct? 我的方法正确吗? I have two routes with the same functionality and different responses. 我有两条具有相同功能和不同响应的路由。 Should I somehow combine these two routes into one? 我应该以某种方式将这两条路线合并为一条吗?

Hmm, I usually have a single route, in your case /news which can receive 2 optional params: pageSize , pageNumber for your pagination purposes. 嗯,我通常只有一条路线,在您的情况下/news可以接收2个可选参数: pageSizepageNumber用于分页。 If those params don't exists than you will offer the first 5 records. 如果这些参数不存在,那么您将提供前5条记录。 If those params are present than you will start providing the other 5 records and based on the calculated offset . 如果存在这些参数,则将基于计算的offset开始提供其他5条记录。

router.get('/news/:pageSize?/:pageNumber?', function (req, res) {
  var language = 'RU';
  var pageSize = req.params.pageSize || 5;
  var pageNumber = req.params.pageNumber || 1;
  var offset = (pageNumber - 1) * pageSize; // If no params are provided than the offset should be 0

  connection.query(queries['news_list'], [language, +pageSize, +offset], function (err, rows) {
    res.json(rows);
  });
});

I am not familiar with optional params in express routes but I hope you get the main idea behind the approach. 我对express routes可选参数不熟悉,但我希望您能理解该方法的主要思想。

You can do ajax requests to load the extra records after the first 5 records are listed. 列出前5条记录后,您可以执行ajax请求以加载额外的记录。

I hope this shined a light on the approach. 我希望这对方法有所启发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM