在我的处理程序中,我希望能够签署JWT,但没有定义' fasttify '。
const postJoinHandler = async (
request: any,
reply: any
): Promise<{ id: string; name: string }> => {
try {
const { username, password } = request.body;
const token = fastify.jwt.sign({ username, password }); //<=== Fastify not defined
return reply.code(201).send(token);
} catch (error) {
request.log.error(error);
return reply.send(400);
}
};
我的模式…
import { postJoinHandler } from '../handlers/auth';
const Token = {
type: 'object',
properties: {
username: { type: 'string' },
password: { type: 'string' },
},
};
const postJoinSchema = {
schema: {
body: {
type: 'object',
required: ['username', 'password', 'email', 'fullname'],
properties: {
name: { type: 'string' },
password: { type: 'string' },
},
},
response: {
201: Token,
},
},
handler: postJoinHandler,
};
export { postJoinSchema };
和我的路线
import { FastifyPluginAsync } from 'fastify';
import { postJoinSchema } from '../schemas/auth';
const auth: FastifyPluginAsync = async (fastify): Promise<void> => {
fastify.post('/auth/join', postJoinSchema);
};
export default auth;
我已经把fastify-jwt
作为插件加载了
const fp = require('fastify-plugin');
module.exports = fp(async function (fastify: any) {
fastify.register(require('fastify-jwt'), {
secret: 'Supersecret!@#',
});
fastify.decorate('authenticate', async function (request: any, reply: any) {
try {
await request.jwtVerify();
} catch (err) {
reply.send(err);
}
});
});
文档在这里
你可以访问fastifyinstance通过请求。只需执行request.server。服务器是fastyinstance,在这里你可以访问你的插件等等。
非常感谢您的回答。我也有同样的问题下面是我的回答://验证密码const isAuth = verifyPassword(请求。密码,foundUser.password);
if (isAuth) {
const { password, salt, ...rest } = foundUser;
console.log("rest", rest);
// generate access token
return { accessToken: request.server.jwt.sign(rest) };
}
所以不调用fastify.jwt.sign()
,你需要使用request.fastify.jwt.sign()