简体   繁体   English

表达自定义 json 响应

[英]Express custom json response

I want to send a custom json response on each request at the end like:我想在最后对每个请求发送自定义 json 响应,例如:

{
  "message": "Something",
  "type": "success",
  "payload": /*object, array, anything else */
}

What I can do is at the end of each request use:我能做的是在每个请求使用结束时:

res.status(200).json({message: 'Something', type: 'success', payload});

If for some reason I want my responses to have another format, I have to go and change each res.json, which is bad.如果出于某种原因我希望我的回复有另一种格式,我必须去更改每个 res.json,这很糟糕。

But since I know all my responses will have this format, is there any way to create a middleware and pass some variables like payload, message, type which gets executed at the end of each request?但是因为我知道我的所有响应都将具有这种格式,有没有办法创建一个中间件并传递一些变量,如有效负载、消息、在每个请求结束时执行的类型?

It is possible to create a midleware for the reponse可以为响应创建一个中间件

router.get('/some-route', controller.someFunction, resposeMiddleware)

You would need to pass the response as an argument on the next call您需要在下一次调用时将响应作为参数传递

someFunction (req, res, next) => {
    res.local.payload = {/* some data */}
    next()
}

the resposeMiddleware would be something like this resposeMiddleware 将是这样的

const resposeMiddleware = (req, res) => {
      const { payload } =  res.local
      res.status(200).json({message: 'Something', type: 'success', payload})
}

Create a helper method like bellow (successResponse.js).创建一个像 bellow (successResponse.js) 这样的辅助方法。 You can also set any property to default.您还可以将任何属性设置为默认值。

    successResponse = (res, statusCode, message, data) => {
      res.status(statusCode || 200).json({
      code: statusCode || 200,
      message: message || "success",
      data: data || {},
    });
   };

   module.exports = successResponse;

now in your controller just import successResponse and use it like现在在您的控制器中只需导入 successResponse 并使用它

successResponse(res, 200, "Your Success message", data);

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

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