NodeJS:无法获取 post 请求文本字段

NodeJS: cannot grab post request text field

我是 Node JS 的新手,所以事情对我来说并不容易。场景是我有输入字段,它将接受多个文件。

<input id="upload-input" type="file" name="uploads[]" multiple="multiple">

在我的 JS 脚本中,我获取了该字段的更改事件,并使用 formData 和 [在不同的端口 运行 对我的上传器应用程序创建了一个 post 请求和 ajax post 方法

$('#upload-input').on('change', function() {
var files = $(this).get(0).files;
if (files.length > 0) {
    var formData = new FormData();
    formData.append('directory', "path/to/directory");
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        formData.append('uploads[]', file, file.name);
    }
    $.ajax({
        url: 'https://myurl.com:3000/upload',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(data) {
            console.log(data);
        },
    });
}
});

现在文件正在发送,在我的后端我可以使用 formidable 上传它,但问题是我无法获得 directory 值,这是我的代码

require('dotenv').load();
var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var session = require('express-session');
app.set('views', __dirname + '/public');
app.use('/uploads', express.static(process.env.USER_UPLOADS))
var cors=require('cors');
app.use(cors({origin:true,credentials: true}));
app.post('/upload', function(req, res) {
    var user_folder = "path/to/directory/";
    var form = new formidable.IncomingForm();
    form.multiples = true;
    form.uploadDir = path.join(__dirname, process.env.USER_UPLOADS + user_folder);
    form.on('file', function(field, file) { fs.rename(file.path, path.join(form.uploadDir, file.name)); });
    form.on('error', function(err) { console.log('An error has occured: \n' + err); });
    form.on('end', function() { res.end('success'); });
    form.parse(req);
});
var server = app.listen(3000, function(){
    console.log('Server listening on port 3000');
});

我试过了

console.log(req.body)

但它 returns undefined,那么如何从后端获取 directory 值?

提前致谢。

为了解决您的问题,我对您的主应用程序的服务器文件进行了一些更改 即 server.js/app.js/index.js 任何适用于您的人。请参阅以下更改:

require('dotenv').load();
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var formidable = require('formidable');
var fs = require('fs');
var session = require('express-session');
var cors=require('cors');

app.set('views', __dirname + '/public');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors({ origin:true, credentials: true }));
app.use('/uploads', express.static(process.env.USER_UPLOADS));


app.post('/upload', function(req, res) {
    var user_folder = "path/to/directory/";
    var form = new formidable.IncomingForm();
    form.multiples = true;
    form.uploadDir = path.join(__dirname, process.env.USER_UPLOADS + user_folder);
    form.on('file', function(field, file) { fs.rename(file.path, path.join(form.uploadDir, file.name)); });
    form.on('error', function(err) { console.log('An error has occured: \n' + err); });
    form.on('end', function() { res.end('success'); });

    // Note the changes here
    form.parse(req, (error, fields, files) => {
      console.log(JSON.stringify({
        fields, // { directory: "path/to/directory" }
        files // contains the uploaded files
    }), null, 2);
  });
});


var server = app.listen(3000, function(){
    console.log('Server listening on port 3000');
});

根据 here 的文档,form.parse 可以采用可选的回调函数。

Parses an incoming node.js request containing form data. If cb is provided, all fields and files are collected and passed to the callback:

form.parse(req, function(err, fields, files) {
  // ... 
});