Node.js、multer 和 req.body 为空

Node.js, multer and req.body empty

这是我的问题,我有一个可以插入文件和字段的表单,但我只收到文件而不收到参数 test!为什么?

这是我的代码:

app.js:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var port = 8000;
var multer = require('multer'); // v1.0.5
var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.originalname.substring(0,file.originalname.lastIndexOf('.')) + '-' + Date.now() + file.originalname.substring(file.originalname.lastIndexOf('.'),file.originalname.length));
  }
});
var upload = multer({ storage : storage}).single('fileUpload');

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

app.post('/api/upload',function(req,res){
    console.log(req.body);
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

app.listen(port, function () {
    console.log('Express server inizializzato sulla porta ' + port);
});

index.html:

<html>
    <head>
        <title>Test upload</title>
    </head>
    <body>
        <form name="form" action="http://localhost:8000/api/upload" method="post" enctype="multipart/form-data">
            <input type="text" name="test" />
            <input type="file" name="fileUpload" />
            <input type="submit" value="invia" />
        </form>
    </body>
</html>

有人可以帮助我吗?

我决定在 post 函数末尾移动 req.body

app.post('/api/upload?:test',function(req,res){

    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    console.log(req.body);

    });
});

如果有人能告诉我为什么我会很高兴学习新事物!但是,现在,我决定了!

2017年更新

From Readme

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

我通过颠倒前端表单对象属性的顺序解决了我的问题:

    var newFormObj  = new FormData();
    newFormObj.append('internalUserID', internalUserID);
    newFormObj.append('listingImage', this.binaryImages[image]);

在后端:

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    console.log(req.body.internalUserID) // YAY, IT'S POPULATED
    cb(null, 'listing-pics/')
  },                    
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }                     
});                     

var upload = multer({ storage: storage });

需要重新整理前端请求的字段,下面我会解释,

I am using multer to upload multiple files and single file in my nodejs application.

邮递员请求截图(错误):

Postman请求截图(正确方法):

查看字段顺序的差异。始终在请求内容的最后附加媒体文件。

我花了将近 2 个小时才找到这个。 绝对工作。试试吧。

将你的 console.log(req.body) 移到 upload(req,res,function(err) {...})

默认的 express body-parser 无法与 multipart/form-data 一起使用,因此我们使用 multer 来解析可在您的上传函数中访问的表单数据。

万一其他人带着像下面这样稍微复杂一些的初始布局来到这里,将上传功能移动到每个路由的文件中并使用它们似乎已经为我解决了这个问题。为什么脾气这么暴躁,我也不知道,老实说,这让我很头疼。

应该注意的是,我有一个自定义存储引擎将文件流式传输到磁盘,这可能导致了这个问题,但它只发生在 1 个特定的路由上,该路由在功能上与其他几个工作相同完美。

希望有一天这会对其他人有所帮助。

初始应用布局

app.ts


import express from 'express';
import multer from 'multer';

import profilePicture from './routes/profile-picture.ts';

const upload = multer();

class Server {
    constructor() {
        this.app = express()
    }

    setRoutes() {
        this.app.use( '/upload', upload.single( 'profile' ), profilePicture );
    }

    // ... other methods
}

profile-picture.ts

import { Router } from 'express';

const profilePicture = Router();

profilePicture.post( '/', ( req, res, next ) => {
    console.log( req.body ); // This was always empty, regardless of field order
    // do something with req
}

出于某种原因更新后的布局

app.ts

import express from 'express';

import profilePicture from './routes/profile-picture.ts';


class Server {
    constructor() {
        this.app = express()
    }

    setRoutes() {
        this.app.use( '/upload', profilePicture );
    }

    // ... other methods
}

profile-picture.ts

import { Router } from 'express';
import multer from 'multer';

const upload = multer();

const profilePicture = Router();

profilePicture.post( '/', upload.single( 'profile' ), ( req, res, next ) => {
    console.log( req.body ); // No longer empty, hooray!
    // do something with req
}