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

Time:10-27

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

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?

CodePudding user response:

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) => {
        //...
     }
};
  • Related