Reputation: 629
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:
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.
Upvotes: 1
Views: 936
Reputation: 10795
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.)
Upvotes: 1