fastify-multer typescript,无法访问request.file

问题描述 投票:0回答:1

这是我第一次使用带有 typescript 的 fastify,sequelize 作为 ORM 和 fastify-multer,当我上传图像时一切正常,但我无法从 request.file 访问文件详细信息,因为 typescript 告诉我 request.file 未定义

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "build": "tsc -p tsconfig.json",
    "start": "nodemon index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "fastify": "^4.13.0",
    "fastify-multer": "^2.0.3",
    "mysql2": "^3.1.2",
    "sequelize": "^6.29.0"
  },
  "devDependencies": {
    "@types/node": "^18.14.2",
    "typescript": "^4.9.5"
  }
}





import { FastifyInstance, RouteGenericInterface } from "fastify";
import SliderController from "./controller";
import SSlider from "./type";
import { Model } from "sequelize";
import { upload } from "../../upload";
module.exports = function Slider(
  app: FastifyInstance,
  prefix: string,
  done: any
) {
 
  app.post(
    "/create",
    { preHandler: upload.single("myfile") },
    async (request, reply) => {
      console.log(request.file); //Property 'file' does not exist on type 'FastifyRequest<RouteGenericInterface, RawServerDefault, IncomingMessage, FastifySchema, FastifyTypeProviderDefault, unknown, FastifyBaseLogger, ResolveFastifyRequestType<...>>
      reply.send("ok");
    }
  );

  done();
};





这张照片是我的错误

Error

node.js typescript sequelize.js multer fastify
1个回答
0
投票

我遇到了同样的问题,显然 .file 变量并不总是存在,我的解决方案是为此类型创建一个扩展。

  1. 首先导入请求并回复输入:

    从“fastify”导入 {FastifyReply, FastifyRequest };

  2. 扩展 FastifyRequest 类型:

    接口 CustomFastifyRequest 扩展 FastifyRequest { 文件?: { 缓冲区:缓冲区; 编码:字符串; 字段名:字符串; mime类型:字符串; 原始名称:字符串; 尺寸:数量; }; }

  3. 设置请求类型为app.post()

    app.post('url', (请求: CustomFastifyRequest , 回复: FastifyRequest ) => { });

使用您的示例看看结果如何:

import { FastifyInstance, RouteGenericInterface, FastifyReply, FastifyRequest } from "fastify";;
import SliderController from "./controller";
import SSlider from "./type";
import { Model } from "sequelize";
import { upload } from "../../upload";
module.exports = function Slider(
  app: FastifyInstance,
  prefix: string,
  done: any
) {

interface CustomFastifyRequest extends FastifyRequest {
    file?: {
      buffer: Buffer;
      encoding: string;
      fieldname: string;
      mimetype: string;
      originalname: string;
      size: number;
    };
  }

  app.post(
    "/create",
    { preHandler: upload.single("myfile") },
    async (request : CustomFastifyRequest , reply : FastifyReply ) => {
      console.log(request.file); //Property 'file' does not exist on type 'FastifyRequest<RouteGenericInterface, RawServerDefault, IncomingMessage, FastifySchema, FastifyTypeProviderDefault, unknown, FastifyBaseLogger, ResolveFastifyRequestType<...>>
      reply.send("ok");
    }
  );

  done();
};
© www.soinside.com 2019 - 2024. All rights reserved.