【问题标题】:Loopback 3 and hook for REST API headersLoopback 3 和 REST API 标头的挂钩
【发布时间】:2020-12-05 10:26:22
【问题描述】:

我有一个使用 loopback 3 并公开 REST API 的旧版应用程序,我想从客户端的传入请求中获取我的 JWT 令牌。我写了一个钩子来访问 req 对象以访问令牌。

Object.keys(app.dataSources).forEach((name: string) => {
    if (camelCase(name) === name) {
        app.dataSources[name].connector.observe('before execute', (ctx, next) => {
            if (!ctx.req.uri) return next(); 
            Object.keys(ctx.req).forEach(function(key) {
                console.log(key, ctx.req[key]);
            }); 
        });
    }
});

路线定义

accepts: [
    {arg: 'codeValue', type: 'string', required: false, http: {source: 'query'}},
    {arg: 'codeId', type: 'string', required: false, http: {source: 'query'}}
]

上述钩子执行时的输出

method GET
uri http://localhost:8010/api/v1/code/100
qs { codeValue: '' } <<== Issue 1
json true
form undefined
headers undefined  <<== Issue 2
timeout undefined

以下是上面强调的问题:

  • 即使我指定了查询参数 codeId,它也没有映射到 req 对象中
  • req 中的标头为 undefined

卷曲命令

curl -H "codeId: TS01" -H "codeValue: 'TS 01" http://localhost:8081/api/v1/code/100

我们计划转为环回版本 4,但这是一个长期过程。任何指针都非常感谢。

【问题讨论】:

    标签: javascript node.js rest loopbackjs loopback4


    【解决方案1】:

    来自 LoopBack 团队的问候 ?

    根据您代码中的以下 sn-p,我假设您正在使用 loopback-connector-rest(或类似的连接器)来调用另一个后端服务的 API。

    app.dataSources[name].connector.observe('before execute'
    

    请注意,before execute 钩子会为您的模型方法发出的传出请求调用。

    要访问 incoming 请求对象,您需要创建一个远程挂钩(请参阅我们的文档中的 Remote hooks)。

    app.remotes().before('**', (ctx, next) => {
      if (!ctx.req.url) return next(); 
      Object.keys(ctx.req).forEach(function(key) {
        console.log(key, ctx.req[key]);
      }); 
    });
    

    (注意传入的请求没有req.uri属性,你应该改用req.url。)

    【讨论】:

    • 嗨米罗斯拉夫。非常感谢,这解决了一个长期存在的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    相关资源
    最近更新 更多