gpt4 book ai didi

typescript - Fastify 多部分/表单数据错误 : "body must be object"

转载 作者:行者123 更新时间:2023-12-03 08:04:22 37 4
gpt4 key购买 nike

我正在使用 fastify-multer 和 JSON Schema 提交可能包含文件的多部分表单数据。无论我做什么,Fastify 总是给我一个错误的响应错误:

{
"statusCode": 400,
"error": "Bad Request",
"message": "body must be object"
}

这是我的index.ts:

const server = fastify();
server.register(require("@fastify/cors"));
server.register(multer.contentParser).after(() => {
if (!isProdEnv) {
server.register(require("@fastify/swagger"), {
/* ... */
});
}
server.register(require("@fastify/auth")).after(() => {
server.decorate("authenticateRequest", authenticateRequest);
server.decorate("requireAuthentication", requireAuthentication);
server.addHook("preHandler", server.auth([server.authenticateRequest]));
server.register(indexRouter);
server.register(authRouter, { prefix: "/auth" });
server.register(usersRouter, { prefix: "/users" });
server.register(listsRouter, { prefix: "/lists" });
server.register(postsRouter, { prefix: "/posts" });
server.register(searchRouter, { prefix: "/search" });
server.register(settingsRouter, { prefix: "/settings" });
});
});
server.setErrorHandler((err, req, res) => {
req.log.error(err.toString());
res.status(500).send(err);
});

以及 /posts/create 端点:

const postsRouter = (server: FastifyInstance, options: FastifyPluginOptions, next: HookHandlerDoneFunction) => {
server.post(
"/create",
{
schema: {
consumes: ["multipart/form-data"],
body: {
content: {
type: "string"
},
media: {
type: "string",
format: "binary"
},
"media-description": {
type: "string"
}
}
},
preHandler: [server.auth([server.requireAuthentication]), uploadMediaFileToCloud]
},
postsController.createPost
);
next();
};

export default postsRouter;

请求 CURL:

curl -X 'POST' \
'http://localhost:3072/posts/create' \
-H 'accept: */*' \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJoYW5kbGUiOiJ1bGtrYSIsInVzZXJJZCI6IjYyNGQ5NmY4NzFhOTI2OGY2YzNjZWExZCIsImlhdCI6MTY1NzEwNTg5NCwiZXhwIjoxNjU3NDA1ODk0fQ.A5WO3M-NhDYGWkILQLVCPfv-Ve-e_Dlm1UYD2vj5UrQ' \
-H 'Content-Type: multipart/form-data' \
-F 'content=Test.' \
-F 'medi<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6c79be6c0cac7cbc38bd1c9cac088d6c8c1" rel="noreferrer noopener nofollow">[email protected]</a>;type=image/png' \
-F 'media-description=' \

为什么这不起作用?

最佳答案

编辑2:显然,有一个非常简单的解决方案:在preValidation Hook 中使用multer而不是preHandler。因此,一段工作代码将如下所示:

server.register(multer.contentParser).after(() => {
server.register(
(instance: FastifyInstance, options: FastifyPluginOptions, next: HookHandlerDoneFunction) => {
instance.post(
"/create",
{
schema: {
consumes: ["multipart/form-data"],
body: {
type: "object",
properties: {
content: {
type: "string"
},
media: {
type: "string",
format: "binary"
}
}
}
},
preValidation: multer({
limits: {
fileSize: 1024 * 1024 * 5
},
storage: multer.memoryStorage()
}).single("media")
},
(request: FastifyRequest, reply: FastifyReply) => {
const content = (request.body as any).content as string;
const file = (request as any).file as File;
if (file) {
delete file.buffer;
}
reply.send({
content,
file: JSON.stringify(file) || "No file selected"
});
}
);
next();
},
{ prefix: "/posts" }
);
});

编辑:在我发布下面的答案后,我找到了解决方案。为可能遇到相同问题的其他人更新我的答案。

首先,我从 fastify-multer 切换到 @fastify/multipart。然后我从 media 字段中删除了 type 属性。

media: {
format: "binary"
}

此后,我在注册@fastify/multipart时添加了选项{ addToBody: true }

import fastifyMultipart from "@fastify/multipart";

server.register(fastifyMultipart, { addToBody: true }).after(() => { ... });

进行这些更改后,media 字段在 request.body 中变得可用。


旧答案:

看来这些天我必须在这里回答我自己的问题。无论如何,我知道发生了什么事。 Fastify 的内置模式验证与 multipart/form-data 配合不佳。我研究了模式规范以确保情况确实如此。所以我从所有路由中删除了模式验证。我的用例是将 API 从 ExpressJS 移植到 Fastify,因此我使用 express-oas-generator 生成了一个很好的 Swagger JSON 规范。躺在周围。我用它来生成 Swagger UI,一切正常。我希望 Fastify 齐心协力解决这个问题。

关于typescript - Fastify 多部分/表单数据错误 : "body must be object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72892620/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com