簡體   English   中英

ExpressJS“錯誤:發送標頭后無法設置標頭。”

[英]ExpressJS “Error: Can't set headers after they are sent.”

因此,我遇到了ExpressJS的問題,似乎找不到解決該問題的文檔。

技術:

  • 正文解析器:1.17.0
  • 快遞4.15.0
  • multer:1.3.0
  • MongoDB的
  • 郵差

視圖當前是3個字段:

  • 名稱(必填)
  • 標語(必填)
  • 圖片(可選)

我想做的是在將任何內容寫入數據庫之前對圖像進行錯誤處理。 圖像只能是mime type image/jpegimage/png以防止HTML內載惡意JS。

我認為問題似乎是我在運行圖像檢查條件並發送多個響應時未正確觸發錯誤,這導致了Error: Can't set headers after they are sent.

drinks.routes.js

var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var multer  = require('multer');
var passport = require('passport');
var config = require('../config/main');
var upload = multer({ dest: 'uploads/images' })

var Drink = require('../models/drinks.model.js');

router.use(function(req, res, next){
  next();
});

...

.post(passport.authenticate('jwt', { session: false }), upload.single('image'), function(err, req, res, next){
  var drink = req.body;
  var drinkImage = req.file;
  if(typeof drinkImage !== "undefined"){
    console.log('image was uploaded');
    if(drinkImage.mimetype !== "image/jpeg" || drinkImage.mimetype !== "image/png" ){
      console.log('Image was not a JPEG or PNG', drinkImage.mimetype);
      res.status(500).send({ error: "Your image was incorrect"});  // >>>>>>>>>>>>>>> The error seems to be coming from here. Unsure of how to properly raise a flag to tell the response to the client. Have tried res.send(), the res.status().send(), res.json(), currently working with next() method to keep going on but not sure how to define err if that is the case
    }
    console.log('image correct mimetype');
  } else {
    drinkImage = {}; // Setting this as an empty object so it doesn't throw an error with the model which is looking for `image: drinkImage.name`
  }
  Drink.createDrink(drink, drinkImage, function(err, drink, drinkImage){
    if(err){
      console.log('Error adding Drink', err);
      res.send(err);
    }
    res.status(200).json(drink)
  });
});

課題研究

此問題歸因於Javascript的異步特性。

響應error 500后,代碼不應執行Drink.createDrink()

if (drinkImage.mimetype !== "image/jpeg" || drinkImage.mimetype !== "image/png" ) {
  console.log('Image was not a JPEG or PNG', drinkImage.mimetype);
  res.status(500).send({ error: "Your image was incorrect"});
  return; // THIS IS VERY IMPORTANT!
}

暫無
暫無

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

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