Coder1000 Coder1000 - 1 month ago 12
Node.js Question

How to upload a file in Node.js ? Error: Cannot POST /upload

PROBLEM:

I click on submit in my upload.ejs and I get the error: "Cannot POST /upload"




SOLUTION:

My problem was an architectural one more than a coding problem.

I changed the structure of my project to solve the problem.

I created a new file called "upload.js" to put the router code in.

I also moved the "upload.ejs" to the root of the project.

I updated my "app.js" to take into account the new router file "upload.js".

I changed the form to use "upload.js".




CODE:

upload.js

var express = require("express");
var router = express.Router();
var flash = require("connect-flash");

var firebase = require("firebase");

var multer = require("multer");
var upload = multer({dest:"./public/images/uploads/"});

router.get("/", function(req, res, next){
res.render("upload");
});

router.post("/", upload.single("image"), function(req, res, next){

if (req.file){
console.log("Uploading file...");
var image = req.file.filename;
}
else {
console.log("No file uploaded");
var image = "noimage.jpg";
}

var post = {
title: req.body.title,
section: req.body.section,
image: image,
}

var section = req.body.section.toLowerCase();

firebase.database().ref("posts/"+section).push(post);

req.flash("success_msg", "Post Created");
res.redirect("/upload");


});

module.exports = router;


upload.ejs

<form enctype="multipart/form-data" method="post" action="upload">

Answer

You are POSTing to /upload url but you the route that you register is POST /users/upload. Possibly you have to move the follwing function into the routes/index.js file:

router.post("/upload", upload.single("image"), function(req, res, next){

    if (req.file){
        console.log("Uploading file...");
        var image = req.file.filename;
    }
    else {
        console.log("No file uploaded");
        var image = "noimage.jpg";
    }

    var post = {
        title: req.body.title,
        section: req.body.section,
        image: image,
    }

    var postRef = fbRef.child("posts");

    postRef.push().set(post);

    req.flash("success_msg", "Post Created")
    res.redirect("/"+ req.body.section.toLowerCase());

});
Comments