首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用multer处理包含表单数据的POST请求时,req.body为[Object: null prototype] {},req.files为空

使用multer处理包含表单数据的POST请求时,req.body为[Object: null prototype] {},req.files为空
EN

Stack Overflow用户
提问于 2020-11-28 03:10:26
回答 1查看 896关注 0票数 0

我正在尝试使用Postman将表单数据发送到Firebase函数上托管的express服务器。这是我用来接收POST请求的代码:

代码语言:javascript
运行
复制
import * as functions from 'firebase-functions';
import express = require('express');
import multer = require('multer');
import * as bodyParser from 'body-parser';

const app = express();
const upload = multer().array("attachment");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.post('/upload', upload, (req, res) => {
    console.log(req.body);
    console.log(req.files);
    res.sendStatus(200);
});

export const server = functions.https.onRequest(app);

这是邮递员的设置

当我发送post请求时,req.body和req.files被记录如下:

代码语言:javascript
运行
复制
i  functions: Beginning execution of "server"
>  [Object: null prototype] {}
>  []
i  functions: Finished "server" in ~1s

我觉得它应该非常简单...我做错了什么?

编辑:

这里请求的是请求头

代码语言:javascript
运行
复制
{
    'postman-token': '816a8871-bb12-470f-93f8-13cb6024815d',
    host: 'localhost:5001',
    'content-type': 'multipart/form-data; boundary=--------------------------115218701862318827186009',
    'content-length': '316657',
    connection: 'close'
}

这是curl代码

代码语言:javascript
运行
复制
curl --location --request POST 'http://localhost:5001/hosting-name/us-central1/server/upload' --form 'testKey="testValue"' --form 'attachment=@ <path_to_your_file>"'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-01 02:12:40

多亏了这篇博客文章,我找到了答案:https://mikesukmanowsky.com/firebase-file-and-image-uploads/

Firebase和Multer不能一起工作。我在我的Typescript项目中修改了博客文章中的代码:

index.ts

代码语言:javascript
运行
复制
import * as functions from 'firebase-functions';
import express = require('express');
import * as bodyParser from 'body-parser';
import formMiddlware from "./formMiddleware";

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.post('/upload', formMiddlware, (req: any, res: any) => {

    console.log(req.body);
    console.log(req.files);

    res.sendStatus(200);


});

export const server = functions.https.onRequest(app);

formMiddleware.ts

代码语言:javascript
运行
复制
import * as Busboy from "busboy";
import os from "os";
import fs from "fs";
import path from "path";

type Dict = {
    [key: string]: any
}

function formMiddlware (req: any , res: any, next: any) {
    // See https://cloud.google.com/functions/docs/writing/http#multipart_data
    const busboy = new Busboy.default({
      headers: req.headers,
      limits: {
        // Cloud functions impose this restriction anyway
        fileSize: 10 * 1024 * 1024,
      }
    });
  
    const fields: Dict = {};
    const files: any[] = [];
    const fileWrites: any[] = [];
    // Note: os.tmpdir() points to an in-memory file system on GCF
    // Thus, any files in it must fit in the instance's memory.
    const tmpdir = os.tmpdir();
  
    busboy.on('field', (key: string, value: any) => {
      // You could do additional deserialization logic here, values will just be
      // strings
      fields[key] = value;
    });
  
    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      const filepath = path.join(tmpdir, filename);
      console.log(`Handling file upload field ${fieldname}: ${filename} (${filepath})`);
      const writeStream = fs.createWriteStream(filepath);
      file.pipe(writeStream);
  
      fileWrites.push(new Promise((resolve, reject) => {
        file.on('end', () => writeStream.end());
        writeStream.on('finish', () => {
          fs.readFile(filepath, (err, buffer) => {
            const size = Buffer.byteLength(buffer);
            console.log(`${filename} is ${size} bytes`);
            if (err) {
              return reject(err);
            }
  
            files.push({
              fieldname,
              originalname: filename,
              encoding,
              mimetype,
              buffer,
              size,
            });
  
            try {
              fs.unlinkSync(filepath);
            } catch (error) {
              return reject(error);
            }
  
            resolve();
          });
        });
        writeStream.on('error', reject);
      }));
    });
  
    busboy.on('finish', () => {
      Promise.all(fileWrites)
        .then(() => {
          req.body = fields;
          req.files = files;
          next();
        })
        .catch(next);
    });
  
    busboy.end(req.rawBody);
}
export default formMiddlware;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65042667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档