[英]REST API - Node, Express, MySQL - How can I filter a JSON (from DB) return by passing a limited number of objects via URL
I'm building a REST API, using Node, Express, MySQL. 我正在使用Node,Express,MySQL构建REST API。
When requesting a list of Node from the http://localhost:3000/Node endpoint, I would like to limit these to only 25 initial records. 当从http:// localhost:3000 / Node端点请求Node列表时,我希望将它们限制为仅25个初始记录。 This could be accomplished with a request like GET http://localhost:3000/Node?maxRecords=25 . 这可以通过类似GET http:// localhost:3000 / Node?maxRecords = 25的请求来完成。
My routes\\Nodes file is: 我的routes \\ Nodes文件是:
var express = require('express');
var router = express.Router();
var Node=require('../models/Node');
router.get('/:id?',function(req,res,next){
if(req.params.id){
Node.getNodeById(req.params.id,function(err,rows){
if(err)
{
res.json(err);
}
else{
res.json(rows);
}
});
}
else{
Node.getAllNodes(function(err,rows){
if(err)
{
res.json(err);
}
else
{
res.json(rows);
}
});
}
});
module.exports=router;
And in my models\\Node.js (that is passing queries to db) is: 在我的models \\ Node.js中(将查询传递给db)是:
var db=require('../dbconnection');
var Node={
getAllNodes:function(callback){
return db.query("Select * from node_link",callback);
},
getNodeById:function(id,callback){
return db.query("select * from node_link where id=?",[id],callback);
}
}
module.exports=Node;
In your models/Node.js: 在您的模型/Node.js中:
getAllNodes: function(maxRecords, callback) {
return db.query("Select * from node_link LIMIT ?", [maxRecords], callback);
}
You can use LIMIT
in the query. 您可以在查询中使用LIMIT
。
http://www.mysqltutorial.org/mysql-limit.aspx http://www.mysqltutorial.org/mysql-limit.aspx
The LIMIT
attribute in your query will help, it will limit the number of rows outputted. 查询中的LIMIT
属性会有所帮助,它将限制输出的行数。
So, with this in mind, your query should look like: 因此,考虑到这一点,您的查询应如下所示:
SELECT * FROM node_link LIMIT 10
If you want more rows, just increase the 10
by whatever you want 😊. 如果要增加行,只需将10
增加任意数量即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.