简体   繁体   中英

Loopback 3 and hook for REST API headers

I have a legacy app which uses loopback 3 and exposes REST API and I wanna get my JWT token from the incoming requests from the clients. I wrote a hook for getting access to the req object to access the token.

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]);
            }); 
        });
    }
});

Route definition

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

The output when the above hook executes

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

Following are issues as highlighted above:

  • Even though I have specified query param codeId , it is not mapped in req object
  • The headers in the req is coming as undefined

Curl command

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

We have plans to move to loopback to version 4, but is a long term process. Any pointers is highly appreciated.

Hello from the LoopBack team

Based on the following snippet in your code, I am assuming you are using loopback-connector-rest (or a similar connector) to call APIs of another backend service.

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

Please note that before execute hook is called for outgoing requests made by your model methods.

To access the incoming request object, you need to create a remote hook instead (see Remote hooks in our docs).

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

(Note that the incoming request does not have req.uri property, you should use req.url instead.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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