我想创建动态 stub 作为 Web 服务。我的想法是在每个请求时加载一个定义文件并返回相应 URL 的数据。 定义文件可能如下所示:
/api/users {users:["john", "jack", "jake"]}
/api/users/1 {user:"john"}
/api/some-data/1 {data:"some data"}
在我代表教程创建的应用程序中,我发现:
router.post('/some-irl', function (req, res) {
//some code
return {some JSON}
});
但是这个定义对我来说看起来是静态的,它应该在我启动 Node.js 之前就存在。是否可以在请求发生时定义/some-irl ?
编辑
实际上,我打算做这样的事情:https://github.com/typicode/json-server但它已经在那里了!
最佳答案
您可以附加一个use
中间件,它可以检查路径并决定是否处理它或传递它:
router.use(function(req, res, next) {
// req.path
// decide what to do
// respond or next()
});
关于javascript - Node.js 中的动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34323309/