如何扩展AdonisJS Response类?

时间:2019-03-08 12:14:13

标签: javascript node.js adonis.js

当用户在我的RESTful应用程序中创建帖子时,我想将响应状态代码设置为201。

我遵循documentation并按如下方式创建了start/hooks.js

'use strict'                                                                                                                      

const { hooks } = require('@adonisjs/ignitor')                                                                                                   

hooks.after.httpServer(() => {                                                                                                                   
  const Response = use('Adonis/Src/Response')                                                                                                    

  Response.macro('sendStatus', (status) => {                                                                                                     
    this.status(status).send(status)                                                                                                             
  })                                                                                                                                             
})

现在在我的PostController.js中,我有这个:

 async store( {request, response, auth} ) {
   const user = await auth.current.user
   response.sendStatus(201)
 }

但是我在此端点上获得了500个HTTP代码。 我在做什么错了?

当我运行Response.hasMacro('sendStatus')时,发现 false

2 个答案:

答案 0 :(得分:1)

事实上,阿多尼斯已经为所有响应代码开箱即用...

只需编写response.created(.....)。

您还可以使用例如:.badRequest()、. notFound()等。 有关更多信息:https://adonisjs.com/docs/4.1/response#_descriptive_methods

答案 1 :(得分:0)

我解决了这个问题yesterday

.woocommerce-product.choice.selected {border:1px solid black;}