我目前正在尝试创建一个 NodeJS 服务器或类似于模型的 REST API,它读取 JSON 文件并使用该数据响应请求。我真的只需要支持 GET 请求。解决这个问题的最佳方法是什么?
这是我到目前为止所拥有的:
/**
* Sample items REST API
*/
function ItemsRepository() {
this.items = [];
}
ItemsRepository.prototype.find = function (id) {
var item = this.items.filter(function(item) {
return item.itemId == id;
})[0];
if (null == item) {
throw new Error('item not found');
}
return item;
}
/**
* Retrieve all items
* items: array of items
*/
ItemsRepository.prototype.findAll = function () {
return this.items;
}
/**
* API
*/
var express = require('express');
var app = express();
var itemRepository = new ItemsRepository();
app.configure(function () {
// used to parse JSON object given in the body request
app.use(express.bodyParser());
});
/**
* HTTP GET /items
* items: the list of items in JSON format
*/
app.get('/items', function (request, response) {
response.json({items: itemRepository.findAll()});
});
/**
* HTTP GET /items/:id
* Param: :id is the unique identifier of the item you want to retrieve
* items: the item with the specified :id in a JSON format
* Error: 404 HTTP code if the item doesn't exists
*/
app.get('/items/:id', function (request, response) {
var itemId = request.params.id;
try {
response.json(itemRepository.find(itemId));
} catch (exception) {
response.send(404);
}
});
app.listen(8080); //to port on which the express server listen
我知道我会使用以下内容来包含该文件,我只是不知道如何将数据填充到 Items 中。
var responseItemsData = require('./items-list.json');
最佳答案
这在 Node 中是微不足道的。您可以直接通过请求.json
文件来加载数据
var responseData = require('./my-json-file'); //.json extension optional
//Do this during your startup code, not during the request handler
然后发送:
res.write(JSON.stringify(responseData));
您需要的其余代码可以在网络上几乎每个 Node.js 教程中轻松获得。
关于javascript - 创建模型 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18602066/