So I'm running into an issue with ExpressJS and can't seem to find documentation to solve the issue.
Tech:
- body-parser: 1.17.0
- express 4.15.0
- multer: 1.3.0
- MongoDB
- Postman
View is currently 3 fields:
- name (required)
- tagline (required)
- image (optional)
What I'm trying to do is Error Handle on the Image before writing anything into the database. The image can only be of mime type
image/jpeg
or image/png
to prevent HTML being uploaded with malicious JS inside.
I believe the issue seems to be that I'm not properly triggering an error while running through the image check conditionals and sending multiple responses which is setting off the 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)
});
});
Topic Research
via Full-Hybrid
No comments:
Post a Comment