Tuesday 6 June 2017

Cannot POST in Node

I attempted to add error handling to my post route and somehow messed up my code. If the error route gets hit it works perfectly. However if the error route is not hit and things are working it cannot post.

I think the error is somehow in this code but I cannot figure it out:

function(err, req, res, next){

Update If I change this to function(req, res, next){ and remove the error handling the post route does work. (However then I'm not handling my error) But if I leave it in no such luck.

How would I correct my code to fix this error?

Thanks for any help!!

router.post("/", middleware.isLoggedIn, upload.array('image', 3), function(err, req, res, next){
// router.post("/", middleware.isLoggedIn, function(req, res, next) {

    // get data from form and add to campgrounds array

      var filepath = undefined;

      var filepath2 = undefined;

      var filepath3 = undefined;

    if(req.files[0]) {
        filepath = req.files[0].key;
    } 

      if(req.files[1]) {
        filepath2 = req.files[1].key;
    } 

     if(req.files[2]) {
        filepath3 = req.files[2].key;
    } 


    //THIS IS THE NEW ERROR ROUTE
    //THIS IS THE NEW ERROR ROUTE
    //THIS IS THE NEW ERROR ROUTE

      if (err){
        console.log('amazing error' + err)
            req.flash("error", err.message);
            res.redirect("back");
      }

    var name = req.body.name;
    var image = filepath;
    var image2 = filepath2;
    var image3 = filepath3;
    var desc = req.body.description;
    var search = req.body.search;
    var price = req.body.price;
    geocoder.geocode(req.body.location, function (err, data) {
    var lat = data.results[0].geometry.location.lat;
    var lng = data.results[0].geometry.location.lng;
    var location = data.results[0].formatted_address;
    var amenities = req.body.amenities;
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var newRentals = {name: name, image: image, image2: image2, image3: image3, description: desc, price: price, search: search, author:author, location: location, lat: lat, lng: lng, amenities: amenities}



    // Create a new campground and save to DB
    Rentals.create(newRentals, function(err, newlyCreated){
        if(err){
            console.log('this2' + err);
        } else {
            // redirect back to campgrounds page
            // res.redirectn("/rentals");
        }
    });
    })
    });



via AndrewLeonardi

No comments:

Post a Comment