javascript - 创建模型 REST API

标签 javascript json node.js rest

我目前正在尝试创建一个 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/

相关文章:

javascript - Chart.js 将数据点减少一半

javascript - 何时使用 HOC。何时使用 Function 作为子函数

javascript - 遍历 JSON 返回未定义?

java - 如何在json中指定特定的对象路径

javascript - HTML5、CSS3、Angular2、TypeScript 用于丰富的 native (桌面)应用程序

javascript - 使用 JavaScript 根据对象的类别更改 Mapbox 标记的类

javascript - 使用 SurveyJS 进行 API 调用和导航控制

iphone - AFNetworking - 如何发出 POST 请求

javascript - 基于 Node.js 的流程管理器如何工作?

javascript - Node JS 关闭读取流