skip to Main Content

I had a working small express app that I used to create a register operation but I felt like it was getting messy so I separated the post request route handler and put it in another file and I feel like I am importing everything correctly but I keep getting the error:

Cannot POST /register

Here’s my server.js file:


  //Creating the express app and hosting it locally
const express=require('express');
const app=express();
const bcrypt=require('bcrypt');
const mysql=require('mysql2');
const flash=require('express-flash');
const session=require('express-session');
const util = require('util'); // Import the util module
const regroute=require('./Register');
  
  // Load environment variables from .env file
  require('dotenv').config();
  const port= process.env.PORT ;
  const host= process.env.DB_HOST;
  const user= process.env.DB_USER;
  const db_name=process.env.DB_NAME;
  const pass=process.env.DB_PASSWORD;
  const sec=process.env.SECRET_SESSION;
  
  
  app.listen(port);
  
  
  ////Creating a database connection object
  const connection = mysql.createConnection({
      host: host,
      user: user,
      password: pass,
      database: db_name
  });
  connection.connect();
  
  // Setting up the view engine (ejs)
app.set('view engine', 'ejs');
  //setting up middlewares
app.use(session({
    secret: sec, // Replace with a strong secret key
    resave: false,
    saveUninitialized: false
}));
app.use(express.urlencoded({extended: false}));
app.use(flash());
app.use('/register',regroute);


  ////Routing
  app.get('/',(req,res)=>{
      res.render('index.ejs');
  });
  
  app.get('/login',(req,res)=>{
      res.render('login.ejs');
  });
  
  app.get('/register',(req,res)=>{
      res.render('register.ejs');
  });
  
    

and here’s my Register.js:

const express=require('express');
const router=express.Router();


router.post('/register',async (req,res)=>{
  const {name,email,password,cpassword}=req.body;
  if(password!=cpassword){
  req.flash('error', 'Passwords do not match');
  return res.redirect('/register');
}

////Setting a query to check if an email already exist

try{
  const queryAsync = util.promisify(connection.query).bind(connection);
  const results = await queryAsync('SELECT * FROM users WHERE email=?', [email]);
    if(results.length> 0 ){
      console.log('email found');
        req.flash('error', 'Email already exists');
        return res.redirect('/register');
    }

const hashedpassword=await bcrypt.hash(password,10);
connection.query('insert into users (user_name,email,password) values (?,?,?)',[name,email,hashedpassword])
}catch(e){
  console.log('here is the error',e);
  req.flash('error','error occured please try again');
  return res.redirect('/register');
}

res.redirect('/login');
});

module.exports=router;

2

Answers


  1. Change this:

    router.post('/register', ...)
    

    to this:

    router.post('/', ...)
    

    You are already using this for the router:

    app.use('/register',regroute);
    

    So, /register is already in the route specification:

    So, when you then do this:

    router.post('/register', ...)
    

    then you’re defining a route for /register/register which is not what you want. The app.use('/register', regrouter) and router.post('/register') are additive.

    The whole router already has /register as a prefix to the URL so defining a route for router.post('/', ...) will give you a route handle for just /register which is what you want.

    Login or Signup to reply.
  2. In your code, you are setting the router to the /register path with this line:

    app.use('/register', regroute)
    

    But in the router code, you also use the /register path:

    router.post('/register', async (req, res)=>{
        // ...
    });
    

    At the end, for accessing the POST method route of your router, you’ll need to send a request to /register/register path and not /register.

    Otherwise, you can solve the error by changing the path of the route in the router, like this:

    router.post('/', async (req, res)=>{
        // ...
    });
    

    This way, you can access the route with the path /register.

    In general, when you configure an express.js router, you set a default path for all the routes in that router.

    E.g.

    index.js

    const myRouter = require('myRouter.js');
    
    // ...
    
    app.use('/app', myRouter);
    

    myRouter.js

    // ...
    
    router.post('/route1', (req, res) => { /* ... */ }); // Accessible at /app/route1
    router.get('/route2', (req, res) => { /* ... */ }); // Accessible at /app/route2
    
    // ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search