Node.js、multer 和 req.body 为空 [英] Node.js, multer and req.body empty

查看:28
本文介绍了Node.js、multer 和 req.body 为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here it is my problem, I have a form where I can insert a file and a field but I receive only the file and not the parameter test! Why?

这是我的代码:

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:

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>

有人可以帮助我吗?

推荐答案

2017年更新

来自自述文件

请注意,req.body 可能尚未完全填充.这取决于客户端向服务器传输字段和文件的顺序.

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.

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

I resolved my issue by reversing the order of my form object properties in the front end:

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

<小时>

在后端:


On the backend:

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 });

这篇关于Node.js、multer 和 req.body 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆