英文:
Fastify: request.params maps to unknown
问题
我是fastify和所有后端js相关的新手。我目前正在开发一个TypeScript/Fastify后端,也许我应该只用JS开始哈哈。
我的问题和这个一样,这个问题有点老了:
https://stackoverflow.com/questions/67288886/fastify-typescript-request-query
这是我的代码:
type ParamsType = { id: string }
const getOpts = {
schema: {
response: {
200: {
type: 'object',
properties: {
id: { type: 'number' },
title: { type: 'string' },
author: { type: 'string' },
imagePath: { type: 'string' },
},
},
},
},
handler: (req: FastifyRequest<{ Params: ParamsType }>, reply: FastifyReply) => {
const { id } = req.params
reply.send(repository.read(id));
}
};
fastify.get('/articles/:id', getOpts);
next();
这里没什么花哨的,但当访问端点时我得到了这个错误:
{"statusCode":500,"error":"Internal Server Error","message":"Cannot read properties of null (reading 'id')"}
这是console.log(req.params)的结果:
{ id: '1' }
此外,我的IDE中在fastify.get
的getOpts
下划线,但在构建时没有触发任何警告或提醒。
任何帮助都将不胜感激!
英文:
I'm new to fastify and all the back-end js stuff. I'm currently working on a TypeScript/Fastify backend which I should maybe have started only with JS lol.
My issue is the same as this one, which is kinda old now:
https://stackoverflow.com/questions/67288886/fastify-typescript-request-query
Here's my code:
type ParamsType = { id: string }
const getOpts = {
schema: {
response: {
200: {
type: 'object',
properties: {
id: { type: 'number' },
title: { type: 'string' },
author: { type: 'string' },
imagePath: { type: 'string' },
},
},
},
},
handler: (req: FastifyRequest<{ Params: ParamsType }>, reply: FastifyReply) => {
const { id } = req.params
reply.send(repository.read(id));
}
};
fastify.get('/articles/:id', getOpts);
next();
Nothing fancy here I guess, but still when reaching the endpoint i get the error:
{"statusCode":500,"error":"Internal Server Error","message":"Cannot read properties of null (reading 'id')"}
Here's the result of console.log(req.params):
{ id: '1' }
Futhermore, the getOpts is underlined in my IDE in the fastify.get but does not trigger any warning or alert when building
Any help is appreciated !
答案1
得分: 2
从代码 reply.send(repository.read(id))
开始,我假设仓库返回一个 Promise
或其他内容。
这不被 Fastify 处理 - 你需要等待结果或使用一个异步函数:
handler: async (req: FastifyRequest<{ Params: ParamsType }>, reply: FastifyReply) => {
const { id } = req.params
return repository.read(id);
}
然后输出将由设置的响应模式进行处理。
英文:
Starting from the code reply.send(repository.read(id))
I assume the repository returns a Promise
or something else.
This is not handled by Fastify - you need to await the result or use an async function:
handler: async (req: FastifyRequest<{ Params: ParamsType }>, reply: FastifyReply) => {
const { id } = req.params
return repository.read(id);
}
Then the output will be processed by the response schema set.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论