我有这段代码:
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var data = {
"word": 1,
"word2": 2,
"word3": 3
}
router.get('/', function(req, res, next) {
res.send(data);
});
module.exports = router;
每当我访问URL API /值时,我都会收到JSON格式的数据,但是,我想添加访问API / values / 1的功能,并只获取数据变量的第一行。我需要添加第二个router.get吗?
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var data = {
"word": 1,
"word2": 2,
"word3": 3
}
router.get('/', function(req, res, next) {
res.send(data);
});
router.get('/:id', function(req, res, next) {
res.send(data);
});
module.exports = router;
我怎么才能只打印JSON变量的第一行而不是全部3?
答案 0 :(得分:1)
你可以这样做:
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var data = {
"word1": 1,
"word2": 2,
"word3": 3
}
router.get('/', function(req, res, next) {
res.send(data);
});
router.get('/:id', function(req, res, next) {
var key = 'word' + req.params.id;
res.send({ [key]: data[key] });
});
module.exports = router;
但是,我会考虑将您的数据结构更改为更合理的方式。也许以下是一个好的开始:
var data = [
{ word: "1" },
{ word: "2" },
{ word: "3" }
];