StrongLoop Loopback:如何自定义HTTP响应代码和标头 [英] StrongLoop Loopback : How to customize HTTP response code and header

查看:231
本文介绍了StrongLoop Loopback:如何自定义HTTP响应代码和标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来自定义StrongLoop LoopBack HTTP响应代码和标题。

I'm looking for a way to customize StrongLoop LoopBack HTTP response code and headers.

我想遵守一些关于REST API的公司业务规则。

I would like to conform to some company business rules regarding REST API.

对于JSON中描述的模型,典型情况是让HTTP响应POST请求,代码为201 +标题Content-Location(而不是loopback的默认响应代码200)没有Content-Location标题)。

Typical case is, for a model described in JSON, to have HTTP to respond to POST request with a code 201 + header Content-Location (instead of loopback's default response code 200 without Content-Location header).

是否可以使用LoopBack执行此操作?

Is it possible to do that using LoopBack ?

推荐答案

不幸的是,这样做的方法有点困难,因为LoopBack不容易有钩子来修改 all 来自API的回复。相反,您需要在引导脚本中为每个模型添加一些代码,这些代码使用 afterRemote 方法挂钩:

Unfortunately the way to do this is a little difficult because LoopBack does not easily have hooks to modify all responses coming out of the API. Instead, you will need to add some code to each model in a boot script which hooks in using the afterRemote method:

/ server / boot / 里面添加一个文件(名称并不重要):

Inside /server/boot/ add a file (the name is not important):

module.exports = function(app) {

  function modifyResponse(ctx, model, next) {
    var status = ctx.res.statusCode;
    if (status && status === 200) {
      status = 201;
    }
    ctx.res.set('Content-Location', 'the internet');
    ctx.res.status(status).end();
  }

  app.models.ModelOne.afterRemote('**', modifyResponse);
  app.models.ModelTwo.afterRemote('**', modifyResponse);
};

这篇关于StrongLoop Loopback:如何自定义HTTP响应代码和标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆