【问题标题】:Best Node based architecture for RESTful API?RESTful API 的最佳基于节点的架构?
【发布时间】:2017-05-09 10:09:55
【问题描述】:

我已经开始开发一个新的应用程序,它的后端只是一个 REST API。我对 Node 还很陌生,所以我从 Express 开始。我仍处于早期阶段,因此我正在寻找有关正确使用框架的建议。

我研究过 Express、Koa、HAPI、LoopBack 和 Restify。我喜欢 Restify,但它似乎不是最流行的选择。我也喜欢 LoopBack 的外观。

我很想以某种形式使用 Swagger / OpenAPI 来记录我的 API。我已经看到了许多 Express 模块,它们也被其他人修改以与 Restify 一起使用。

有什么建议吗?谢谢!

【问题讨论】:

    标签: node.js rest


    【解决方案1】:

    有大量对 Express 的支持,但您几乎可以将所有您喜欢使用的东西混合在一起。我喜欢使用 node-mysql 节点模块,这样我就可以在后端使用 mysql。老实说,我只是创建自己的 API。它们真的很容易构建。您只需在 js 文件中定义路由,然后为每个端点定义获取、发布和删除函数。我希望这会有所帮助。

    编辑:这是一个使用 NodeJS、Express 和 MySQL 制作 REST API 的教程。如果您知道自己在用 javascript 做什么,那么这将使您在不到几个小时的时间内起床并开始工作。

    http://www.yogasaikrishna.com/simple-restful-api-using-nodejs-express-and-mysql/

    【讨论】:

      【解决方案2】:

      如果您是 Node.js 新手,我会继续使用 express。它有很多documentation,非常灵活,并且得到积极维护。使用 express 可以轻松利用 CRUD 并使用 JSON 进行响应。它包括一个路由器,例如,这可以更轻松地为路由添加前缀,例如 /api/v1 并包含应用程序特定部分的中间件,这使得在一个服务器上维护多个版本的 API 变得更容易。一个简单的回显路由很简单:

      var express = require('express')
      var bodyParser = require('body-parser')
      
      var app = express()
      router = express.Router()
      // Use middleware to parse JSON request body
      router.use(bodyParser.json())
      
      // prefix router with /api/v1/router
      app.use('/api/v1', router)
      
      // /api/v1/echo route
      router.post('/echo', function(req, res) {
          // read the property message from the request body
          var message = req.body.message
      
          // check if message from request body is not null
          // if it it not, respond with a status of 200 and
          // send message back to client.
          // if message was null, respond with a status of
          // 400 (bad request) with an object containing
          // an error property indicating the request body is
          // missing the message property
          if(message)
              res.status(200).send({
                  message: message
              })
          else
              res.status(400).send({
                  errors: 'No message property in request body.'
              })
      })
      
      app.listen(3000, function(err) {
          if(err)
              return console.error(err)
      
          console.log('Server listening at http://localhost:3000/')
      })
      

      【讨论】:

        【解决方案3】:

        我听说sails.js 有一个非常强大的cli,可以让你的路线快速启动和运行。

        我个人喜欢 Express,因为大多数人都使用它,如果您学习 Express,那么您将能够相当轻松地阅读许多其他开发人员的 API 代码。一旦你学习了 express,你可能想尝试其他框架,但在那之前我建议只使用 Express。

        我听说还有一些框架专注于安全性。如果您喜欢安全实践,则可能需要研究一下。

        Socket.io 非常棒,可以让您实时查看服务器上的更新。 Hapi.js 似乎是最流行的。我只用过 express,也玩过 Socket.io,但我肯定会同时学习 Express 和 Socket.io

        【讨论】:

          猜你喜欢
          • 2017-10-15
          • 2014-03-24
          • 2015-08-29
          • 1970-01-01
          • 2013-03-27
          • 1970-01-01
          • 1970-01-01
          • 2017-07-16
          • 2012-03-04
          相关资源
          最近更新 更多