NodeJS Post Request "Cannot POST /upload"

Issue

I am trying to make a simple upload function on my web application created in NodeJS. I have a route to /admin that I am using to render the form page. Below is the HTML of the /admin.handlebars page.

<body>
  <div class = "container">
    <div class = "row">
      <div class = "col-md-6 m-auto">
        <h1 class = "text-center display-4 my-4">Upload Tutorial Template</h1>
        <form action = "./upload" method ="POST" enctype="multipart/form-data">
          <div class="custom-file mb-3">
            <input type="file" name="file" id="file" class="custom-file-input">
            <label for = "file" class="custom-file-label">Choose Video</label>
            </div
        </form>
        <input type="submit" value="Submit" class="btn btn-primary btn-block"
      </div>
    </div>
  </div>`

The part of the admin.js file that handles the post request is displayed below, currently I am trying to render on screen the file name, but instead when I click the sumbmit button the screen displays “Cannot POST /upload”.

router.get('/', function (req, res) {
  console.log("Rendered Upload page")
  res.render('admin');
});

//route of post to upoad, Uploads file to db
router.post('/upload', upload.single('file'), function (req, res) {
  console.log("Post made")
  res.response({file: req.file});
});

Edit, the main app.js file also.

 var express = require('express');
 var path = require('path');
 var cookieParser = require('cookie-parser');
 var bodyParser = require('body-parser');
 var exphbs = require('express-handlebars');
 var expressValidator = require('express-validator');
 var flash = require('connect-flash');
 var session = require('express-session');
 var passport = require('passport');
 var LocalStrategy = require('passport-local').Strategy;
 var mongo = require('mongodb');
 var mongoose = require('mongoose');


 //Mongoose Part
 mongoose.connect('mongodb://localhost/loginapp');
 //mongodb
 var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');
var admin = require('./routes/admin');

//start app
// using express for first time to initialize
var app = express();

//Viewing engine start here\
// views folder to handle views
app.set('views', path.join(__dirname, 'views'));
// set hanglebards ass the engine, default layout called layout.handlebars
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
//set to handlebards
app.set('view engine', 'handlebars');
//images
// app.set('view engine', 'ejs')

app.use(express.static('views/images'));

//Middleware config
//Video Tutorial
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());

// Public Folder to hold images, jquery, stylesheets
app.use(express.static(path.join(__dirname, 'public')));

//use of Express session
app.use(session({
  secret: 'secret',
  saveUnitialized: true,
  resave: true
}));

//PASSPORT INNIT FOR VALIDATIOn
app.use(passport.initialize());
app.use(passport.session());

//Express Validator from https://devhub.io/repos/ctavan-express-validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

//connect the flash
app.use(flash());

//set GLOBAL variables for flash messages
app.use(function (req, res, next) {
  //response local sucess message = require flash 'sucess msg'
  res.locals.sucess_msg = req.flash('sucess_msg');
  res.locals.error_msg = req.flash('error_msg');
  //passport error messages
  res.locals.error = req.flash('error');
  //for the nav bar when logged inspect
  res.locals.user = req.user || null;
  next();
});


app.use('/', routes);
// ADMIN BELOW
app.use('/admin', admin);
//UPLAOD BIT
app.use('/users', users);

//Setting the port for the page/app
app.set('port', (process.env.PORT || 3000));

app.listen(app.get('port'), function(){
  console.log('Server Started on Port '+app.get('port'));
})

Solution

Not sure of your server configuration, but you can try below

const port = 3000;

var express = require('express'),
    app = express();
var bodyParser = require('body-parser');

app.use(express.static(__dirname + '/public'));

app.use(bodyParser.urlencoded({
   extended: false;
}));

app.use(bodyParser.json());

router.get('/', function (req, res) {
  console.log("Rendered Upload page")
  res.render('admin');
});

router.post('/upload', upload.single('file'), function (req, res) {
  console.log("Post made")
  res.response({file: req.file});
});

app.listen(port);

Answered By – Suresh Prajapati

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published