我是一个 JavaScript 和 React 菜鸟。我正在使用 TypeScript、React、Sequelize 和 postgres 为数据库创建一个项目。
我正在尝试使用 Fastify 访问我的
request.body
路线中的 quantity
成员 post
。我将主体的类型传递给我的 post
中间件中的 Fastify。当我console.log()
整个body
时,我可以看到正确的数量,但是当我单独提取quantity
时,值为undefined
。
interface IMyInterfaceCreateBody {
quantity: number;
}
interface IMyInterfacePostReply {
200: { items: MyObject[] };
201: { items: MyObject[] };
302: { url: string };
'4xx': { error: string };
}
const myRoute: FastifyPluginAsync = (fastify): Promise<void> => {
fastify.post<{
Body: IMyInterfaceCreateBody;
Reply: IMyInterfacePostReply;
}>('/myRoute', async function (request, reply) {
const newItems: MyObject[] = [];
const body: IMyInterfaceCreateBody = request.body;
console.log(body);
const quantity: number = body.quantity;
console.log(quantity);
for (let i = 0; i < quantity; i++) {
const newMyObject = await MyObject.create({
id: uuid(),
});
console.log(newMyObject);
newItems.push(newMyObject);
}
await reply.code(201).send({ items: newItems });
});
return Promise.resolve();
};
控制台输出:
[App] {"quantity":1}
[App] undefined
我相信这可能与使用 Fastify 挂钩提取原始数据有关,但我不确定。
谢谢。
我已经尝试过:
将数量值直接提取到变量类型数字中
先提取,将整个body放到一个接口实例中,单独提取数量值,但是该值变成了undefined
我期望使用邮政路线时通过的数量值。
这可能是因为 Fastify 未正确解析请求正文,导致
quantity
字段为 undefined
。
通过确保正确的正文解析、正确的请求结构和匹配的内容类型,您应该解决
quantity
为 undefined
的问题。
import { FastifyPluginAsync } from 'fastify';
import { v4 as uuid } from 'uuid';
import MyObject from './models/MyObject'; // Adjust this import according to your project structure
/**
* Interface representing the expected structure of the request body for creating items.
*/
interface IMyInterfaceCreateBody {
/** The quantity of items to create */
quantity: number;
}
/**
* Interface representing the possible response structures for the POST request.
*/
interface IMyInterfacePostReply {
200: { items: MyObject[] };
201: { items: MyObject[] };
302: { url: string };
'4xx': { error: string };
}
/**
* Fastify plugin that defines the POST route for creating items.
* This route expects a request body that includes a `quantity` field.
* It responds with a list of created items or an error message.
*
* @param fastify - The Fastify instance
* @returns A promise that resolves when the plugin is registered
*/
const myRoute: FastifyPluginAsync = async (fastify): Promise<void> => {
// Ensure the body parser is registered (Fastify handles JSON by default, but this ensures form data is parsed)
fastify.register(require('@fastify/formbody'));
fastify.post<{
Body: IMyInterfaceCreateBody;
Reply: IMyInterfacePostReply;
}>('/myRoute', async function (request, reply) {
const newItems: MyObject[] = [];
const body: IMyInterfaceCreateBody = request.body;
// Log the entire body to verify the structure during debugging
console.log('Full body:', body);
// Extract and log the quantity to ensure it's correctly extracted
const quantity: number = body.quantity;
console.log('Quantity:', quantity);
// Validate that quantity is a number before proceeding
if (typeof quantity !== 'number') {
return reply.code(400).send({ error: 'Invalid quantity' });
}
// Create the specified quantity of new MyObject instances
for (let i = 0; i < quantity; i++) {
const newMyObject = await MyObject.create({
id: uuid(), // Generate a unique ID for each new object
});
console.log(newMyObject); // Log the newly created object for debugging
newItems.push(newMyObject); // Add the new object to the list of items to be returned
}
// Send the response with the newly created items and a 201 status code
await reply.code(201).send({ items: newItems });
});
return Promise.resolve(); // Return a resolved promise when the plugin is registered
};
export default myRoute;
通过注册插件,您可以确保 Fastify 的主体解析器正确注册以处理 JSON 或表单数据。
app.register(require('@fastify/formbody'));
这确保 Fastify 可以正确解析传入的请求正文,特别是在您发送
application/x-www-form-urlencoded
数据时。如果您发送 JSON,Fastify 默认设置为处理 application/json
请求。
验证传入的请求结构是否符合 TypeScript 接口的期望至关重要。您可以记录整个
request.body
来检查数据结构是否符合预期:
console.log('Full body:', request.body);
确保请求的
Content-Type
标头正确(例如,如果您要发送 JSON 数据,则为 application/json
)。内容类型不匹配可能会导致正文解析错误,从而导致未定义的字段。
仔细检查发送请求的客户端代码或工具(如 Postman),以确保它包含
quantity
字段,并且该字段的格式正确为数字。