簡體   English   中英

嘗試將圖像和用戶數據上載到mongoDB時收到錯誤消息“發送后無法設置集頭”

[英]Getting error “Cant set headers after they are sent” when trying to upload image and user data to mongoDB

我正在使用Node,Express,Mongo和Angular制作簡單的應用程序。 我有一個表單,用戶可以在其中插入數據並上傳圖像。 對於圖像上傳,我使用ng-file-upload 我正在使用多方獲取表單數據。 這是我的API,用於將圖像上傳到服務器文件夾,並與文件名一起保存並輸入到用戶數據的mongdb中。

router.route('/upload/image')
    .post(function(req, res){
    var form = new multiparty.Form();
    form.parse(req, function(err, fields, files) {
        console.log(files);
        console.log(fields);
        var file = files.file[0];
        var contentType = file.headers['content-type'];
        var tmpPath = file.path;
        var extIndex = tmpPath.lastIndexOf('.');
        var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex);
        // uuid is for generating unique filenames.
        var fileName = uuid.v4() + extension;
        var destPath = './public/img/' + fileName;

        // Server side file type checker.
        if (contentType !== 'image/png' && contentType !== 'image/jpeg' && contentType !== 'image/jpg') {
            fs.unlink(tmpPath);
            return res.status(400).send('Unsupported file type.');
        }

        fs.rename(tmpPath, destPath, function(err) {
            if (err) {
                return res.status(400).send('Image is not saved:');
            }
            return res.json(destPath);
        });

        var user = new User();
        user.firstName = fields.firstName;
        user.lastName = fields.lastName;
        user.email = fields.email;
        user.numOfCups = fields.numOfCups;
        user.currentBalance = fields.currentBalance;
        user.totalNumOfCups = fields.numOfCups;
        user.totalMoneySpent = fields.currentBalance;
        user.photo = destPath;

        user.save(function(err, user){
            if(err){
                return res.send(500, err);
            }
            return res.json(user);
        });
    });
});

當我將用戶數據保存在UI中時,它會將文件復制到服務器文件夾中,但不會將數據保存到mongodb中,並引發錯誤- “發送后無法設置標頭” 我知道它與兩次調用res.json ,但是我該如何解決呢? 任何指針深表贊賞。

您不能發送多個回復。

修復:刪除return res.json(destPath); 並將您從創建用戶到保存實體的所有代碼替換為return res.json(destPath);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM