[英]How to get the return value from the hook of fastify?
How to pass parameters from hooks to request handler in Fastify?如何将参数从钩子传递到 Fastify 中的请求处理程序?
For example, I want to get the username
in the BasicAuth hook from the request.例如,我想从请求中获取 BasicAuth 挂钩中的
username
。
const fastify = require('fastify')()
const authenticate = {realm: 'Westeros'}
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
function validate (username, password, req, reply, done) {
if (username === 'Tyrion' && password === 'wine') {
// How to return username from here?
done()
} else {
done(new Error('Winter is coming'))
}
}
fastify.after(() => {
fastify.addHook('onRequest', fastify.basicAuth)
fastify.get('/', (req, reply) => {
// How to get the username here?
})
})
You need to attach it to the request
object:您需要将其附加到
request
object 中:
const fastify = require('fastify')()
const authenticate = { realm: 'Westeros' }
fastify.register(require('@fastify/basic-auth'), { validate, authenticate })
// this decoration will help the V8 engine to improve the memory allocation for the request object
fastify.decorateRequest('user', null)
function validate(username, password, req, reply, done) {
if (username === 'Tyrion' && password === 'wine') {
// add it to the
req.user = { username }
done()
} else {
done(new Error('Winter is coming'))
}
}
fastify.after(() => {
fastify.addHook('onRequest', fastify.basicAuth)
fastify.get('/', async (req, reply) => {
return { hello: req.user.username }
})
})
fastify.inject({
method: 'GET',
url: '/',
headers: {
authorization: 'Basic ' + Buffer.from('Tyrion:wine').toString('base64')
}
}, (err, res) => {
console.log(res.payload)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.