所以我得到了具有以下两个功能的 Store.js:
select: function(type, id) {
var list = memory[type];
id = parseInt(id);
list = (list == undefined || list.length === 0)? undefined: list; // prevent []
if (list != undefined && list.length > 0 && !isNaN(id)) {
list = list.filter(function(element) {
return element.id === id;
});
list = (list.length === 0)? undefined: list[0]; // only return the 1 found element; prevent empty []
}
return getDeepObjectCopy(list); // may contain undefined, object or array;
},
insert: function(type, element) {
checkElement(element);
if (element.id !== undefined) {
throw new Error("element already has an .id value, but should not on insert!",e);
}
element.id = globalCounter();
memory[type] = memory[type] || [];
memory[type].push(getDeepObjectCopy(element));
return element.id;
},
在我的 Videos.js 中我得到了这条路线。我如何将数据发布到此商店以及如何取回数据?
videos.route('/')
.get(function(req, res, next) {
store.select(req)
next();
})
.post(function(req,res,next) {
store.insert(/json/ , {
"title": req.param.name,
})
next();
});
最佳答案
编辑
我的回答有点不对劲。
验证请求和发送响应的方式有点奇怪。
您的代码应该看起来更像这样:
videos.route('/')
.get(function(req, res, next) {
if(!req.accepts('json')) {
res.status(406).send('response of application/json only supported, please accept this');
}
res.send(getVideos());
})
.post(function(req,res,next) {
if(!( /application\/json/.test(req.get('Content-Type')))) {
res.status(415).send('wrong Content-Type'); // user has SEND the wrong type
return;
}
const item = store.insert(/json/ , {
"title": req.body.name,
})
res.send(item);
});
insert: function(type, element) {
checkElement(element);
if (element.id !== undefined) {
throw new Error("element already has an .id value, but should not on insert!",e);
}
element.id = globalCounter();
memory[type] = memory[type] || [];
return memory[type];
}
内容的验证可以进入中间件函数,而不是直接进入路由器 Controller 回调。但这段代码可以帮助您了解如何处理请求。
希望这有帮助
关于node.js - ExpressJS 路由将参数保存到 Store.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52039208/