Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Path exists in expressjs but says POST 404 (Not Found)

So I am stuck on a very basic route error.

Project Structure:

- controllers
   authentication.js
- routes
   auth.js
   pages.js
- views
   register.html
- server.js

Respective codes

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

controllers/authentication.js

//...
exports.register = upload.none(), function (req, res) {
  //...
}
//...

routes/auth.js

const express = require('express');
const authController = require("../controllers/authentication");
const router = express.Router();
router.post('/register', authController.register);
module.exports = router;

routes/pages.js

const express = require('express');
const router = express.Router();
router.get('/register', (req, res) => {
    res.render('register');
});
module.exports = router;

views/register.html

//...
<form action="/auth/register" method="POST" enctype="multipart/form-data" id="myForm">
/...

server.js

const express = require('express');
const path = require('path');
const app = express();
const { dirname } = require('path');
const publicDirectory = path.join(__dirname, './public');
app.use(express.static(publicDirectory));
app.set('view engine', 'html');
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
app.listen(8080, () => {
    console.log('Server listening on port http://localhost:8080');
});

When I submit the form the console says
POST http://localhost:8080/auth/register 404 (Not Found).

But if I skip the controllers/authentication.js part and define every thing from exports.register in routes/auth.js in router.post('/register', ....); it works just fine.

What could I be doing wrong?

>Solution :

Try placing register middleware in an array, now it’s exporting only upload:

//...
exports.register = [upload.none(), function (req, res) {
  //...
}];
//...

or you could move upload middleware to the register middleware and call it from there:

const upload = multer().none();

exports.register = (req, res, next) => {

     upload(req, res, (err) => {
        //...
     }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading