![](/img/trans.png)
[英]Cannot read properties of undefined (reading 'rows') ------ How can I solve this problem?
[英]How can i solve this error 'Cannot read properties of undefined (reading 'sign')' on fastify
我正在为我的后端实现一个 JWT 生成器,但是当使用 fastify 方式时,我得到了这个错误:
无法读取未定义的属性(读取“符号”)
所以我在这里卡住了。
有人会知道原因,我附上我的代码片段。
import fetch from "node-fetch";
import { randomBytes, createHash } from "crypto";
import { PrismaClient, users } from ".prisma/client";
import { Jwt, JwtPayload } from "jsonwebtoken";
import HttpsProxyAgent from "https-proxy-agent";
const proxyAgent = HttpsProxyAgent("http://148.201.1.200:3128");
const fastify = require('fastify')()
function genRandomString(length) {
return randomBytes(Math.ceil(length)).toString("hex").slice(0, length);
}
function generateJWTToken(user: users) {
const { password, sal, active, ...enviar } = user;
const token = fastify.jwt.sign({
...enviar,
});
console.log(token);
const decoded: Jwt = fastify.jwt.decode(token, { complete: true });
return {
token,
uuid: user.id,
nombre: `${user.name} ${user.lastname_p} ${user.lastname_m}`,
exp: (decoded.payload as JwtPayload).exp,
};
}
main.ts
async function main() {
app.register(require("@fastify/swagger"), swaggerOptions);
app.register(require('@fastify/jwt'), {
secret: 'supersecret'
})
app.decorate("prisma", prisma);
app.register(require("@fastify/cors"), {
origin: "*",
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "Accept"],
});
app
.register(authRouterWeb, {
prefix: "/api/v1/auth-web",
});
app.listen(port, (err, address) => {
if (err) {
app.log.error(err);
process.exit(1);
}
app.log.info(`server listening on ${address}`);
});
}
因此,如果您有任何建议或其他替代方法来更改或改进我的代码,请不胜感激。
此错误意味着执行此行时fastify.jwt
undefined
:
// fastify.jwt === undefined, you cannot access anything from it
const token = fastify.jwt.sign({
...enviar,
});
从https://github.com/fastify/fastify-jwt阅读文档,我假设您需要通过调用以下代码来创建 JWT 令牌:
fastify.register(require('@fastify/jwt'), {
secret: 'supersecret'
})
你也可以在这里找到有用的信息: Fastify not defined when trying to sign a jwt with fastify-jwt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.