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

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

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

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

在我的JS脚本中,我抓住了这个字段的change事件,并使用formDataajax 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)

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

提前致谢。

javascript node.js ajax formidable
1个回答
1
投票

为了解决您的问题,我对主应用程序的服务器文件进行了一些更改,即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可以采用可选的回调函数。

解析包含表单数据的传入node.js请求。如果提供了cb,则会收集所有字段和文件并将其传递给回调:

form.parse(req, function(err, fields, files) {
  // ... 
});
© www.soinside.com 2019 - 2024. All rights reserved.