简体   繁体   English

AdonisJs可以用于REST APIS吗?

[英]Can AdonisJs be used for REST APIS?

Sorry for a nooby question. 抱歉,这是一个不起眼的问题。 I'd ask it anyway! 无论如何我会问它! I am playing around with AdonisJs. 我正在玩AdonisJs。 I understand it is a MVC framework. 我知道它是一个MVC框架。 But I want to write REST APIs using the said framework. 但我想使用上述框架编写REST APIs I could not find much help on the internet. 我在互联网上找不到多少帮助。

I have two questions: 我有两个问题:

  1. Does the framework support writing REST APIs? 框架是否支持编写REST API?
  2. If yes to 1. then what could be the best starting point? 如果是1.然后可能是最好的起点?

1. I've created 3 API projects with AdonisJS and think it's ideal for quick setup. 1.我用AdonisJS创建了3个API项目,并认为它是快速设置的理想选择。 It has many functions already included from start, supports database migrations and is pretty well documented in general. 它从开始就已包含许多功能,支持数据库迁移,并且通常都有很好的文档记录。

You can create routes easily with JSON responses: http://adonisjs.com/docs/3.2/response 您可以使用JSON响应轻松创建路由: http//adonisjs.com/docs/3.2/response

Route.get('/', function * (request, response) {
  const users = yield User.all()
  response.json(users)
})

Or add them to a controller, and even fairly easily add route authentication with token protection (all documented): 或者将它们添加到控制器,甚至可以相当容易地添加带有令牌保护的路由身份验证(所有记录):

Route.post('my_api/v1/authenticate', 'ApiController.authenticate')

Route.group('api', function () {
  Route.get('users', 'ApiController.getUsers')
}).prefix('my_api/v1').middleware('auth:api')

2. Take a look at the official tutorial, you can probably finish it in about half an hour. 2.看看官方教程,你可以在大约半小时内完成它。 http://adonisjs.com/docs/3.2/overview#_simplest_example http://adonisjs.com/docs/3.2/overview#_simplest_example

  • Start with defining some routes and try out echoing simple variables with JSON and just in regular views. 首先定义一些路由,然后尝试使用JSON回显简单变量,并在常规视图中使用。
  • Move the test logic to Controllers 将测试逻辑移动到控制器
  • Read a bit more about the database migrations and add some simple models. 阅读有关数据库迁移的更多信息并添加一些简单模型。
  • Don't forget the Commands and Factory, as you can easily define test data commands there. 不要忘记命令和工厂,因为您可以在那里轻松定义测试数据命令。 This will save you a lot of time in the long run. 从长远来看,这将为您节省大量时间。

Just keep in mind that you need to have a server with Node.JS installed to run the system on production (personally I'm keeping it running using a tool like Node Forever JS. 请记住,您需要安装一个安装了Node.JS的服务器才能在生产中运行系统(就我个人而言,我使用Node Forever JS等工具保持运行。

In order to create just a RESTful api you can use 为了创建一个RESTful api,你可以使用

npm i -g @adonisjs/cli
# Create a new Adonis app
adonis new project-name --api-only

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM