如何使用中间件加密adonis js 5响应数据



我想使用中间件加密adonis js 5响应发送的数据。

我以这种方式从我的服务类api返回响应数据到react前端:

public async login(username:string,password:string)
{
return {'status':'success','data':{'username':username,'password':password }};
}

现在我想在adonis js 5中间件中获得这些数据,并首先加密它,然后发送到客户端。我无法在adonis js 5中间件中获得返回的响应数据。请帮帮我。

  • 使用adonis cli创建一个新的中间件类,假设是EncryptMiddleware。源
node ace make:middleware EncryptMiddleware
  • kernel.ts文件中注册您的中间件文件为全局或命名中间件。源
/*
|--------------------------------------------------------------------------
| Global middleware
|--------------------------------------------------------------------------
*/
Server.middleware.register([() => import('App/Middleware/EncryptMiddleware')])

/*
|--------------------------------------------------------------------------
| Named middleware
|--------------------------------------------------------------------------
*/
Server.middleware.registerNamed({ encryptResponse: () => import('App/Middleware/EncryptMiddleware') })
  • 如果你使用命名中间件,那么你必须在每个路由或路由组上使用它。例如:
Route.get('dashboard', 'DashboardController.index').middleware('encryptResponse') // 👈
  • 现在将您的加密逻辑添加到App/Middleware/EncryptMiddleware中的EncryptMiddleware类。源
import Encryption from '@ioc:Adonis/Core/Encryption'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
export default class EncryptMiddleware {
public async handle(
{ response, request }: HttpContextContract,
next: () => Promise<void>
) {
// Some encryption logic => e.g. encrypt body here
const encryptedResponse = Encryption.encrypt(request.body())
// Send encrypted data to the response
response.send(encryptedResponse)
await next()
}
}
  • 结果:您将获得加密的响应体,现在您需要在客户端上解密响应。