【问题标题】:ajax not able to capture response from Node Express in multerajax 无法在 multer 中捕获来自 Node Express 的响应
【发布时间】:2018-01-13 20:42:29
【问题描述】:

我正在使用 multer 上传图像,效果很好,我可以看到打印到控制台的数据,但我不确定如何捕获这些数据并在浏览器中对其进行操作。以下是我的代码:

var multer = require("multer");
var storage = multer.diskStorage({
    destination: function(req, file, callback){
        callback(null, 'uploads'); // set the destination
    },
    filename: function(req, file, callback){
        callback(null, 'FILE1' + '.jpg'); // set the file name and extension
    }
});
var upload = multer({storage: storage});
app.post('/', upload.any(), function(req, res, next) {
  console.log(req.files);
    var image = req.files;
    console.log(image);
    res.send(image); //this should come to jquery response object in browser, but not sure why it is not
});

以下是我的 jquery 代码,应该能够在响应对象中获取上述数据:

$('body').on('click', '#uploadFile', function (event) {

            $.ajax({
                type: 'POST',
                url: '/',
                success: function (response) { //this is always "" not sure why, I am expecting multer response to be here
                    console.log('successfully uploaded', response);
                },
                error: function () {
                    console.log('coudn\'t upload');
                }
            });
            //return false;
        })

我认为问题在于,当我在 jquery 中捕获响应时,multer 尚未上传文件,因此我在 ajax 中没有响应或响应为空白。我不确定如何解决这个问题。

【问题讨论】:

  • 您是否检查了网络选项卡以查看实际得到的响应? jQuery 尝试解析响应,所以这可能是它变为空的原因。
  • 我在网络标签中得到了正确的响应。
  • 尝试将请求中的接受标头设置为您期望响应的文件类型。
  • 这不会解决它,因为我已经尝试过了。我认为问题在于,当我在 jquery 中捕获响应时,multer 还没有上传文件,所以我在 ajax 中没有响应或响应为空白。我不知道如何解决这个问题。
  • 这看起来很奇怪。 Multer 在将文件保存到磁盘之前不应调用next()

标签: javascript jquery node.js express multer


【解决方案1】:
app.post('/', upload.any(), function(req, res, next) {
    console.log(req.files);
    var image = req.files;
    console.log(image);
    res.send(image); // this should come to jQuery response object
    res.end();  // !!! - note this!
});

您必须添加res.end() 才能完成回复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 2018-07-12
    • 2023-03-21
    • 2020-09-06
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多