Search code examples
javascriptnode.jsaws-sdk-nodejs

Node js route not working,always shows cannot post


I have referred few answers on stackoverflow too,but still not working. When i use app.post function in app.js with a function it works but when i put route inside it it doesnt work and postman says cannot post. It was working fine 1 day ago.
Here is the code of app.js

let express=require("express");
let app=express();
let signuproute=require("./routes/signup");
app.listen(3000,function(req,res){
console.log("server started");

});

app.get("/",function(req,res){

  console.log("home page called");
  res.send({message:"Thanks for calling home page"});
});

app.post("/signup",signuproute);

the above signup route doesnt work but when i directly pass the function in it like

 app.post("/signup",function(req,res){ console.log("signed up"); });

It prints signed up on console. So Why does the route is not working.

Here is my signed up route, signup.js:

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

console.log("Signup called");
router.get("/",function(req,res){

});
router.post("/",function(req,res,next){

  res.send({message:"thank you for signing up"});
});
module.exports=router;

Solution

  • The problem is that you already defined a post route handler in routes/signup.js file. Hence it is have no sense to write app.post(router.post(function (req, res, next) {}).

    You have to use app.use function as stated in express.JS API references.

    Think about app.use('/signup', signupRoute) as /signup namespace for common SignUp functionality. For example in the future you may want to reuse SignUp functionality with /user/create route like this app.use('/user/create', signupRoute).

    Here is how your example should looks like:

    let express = require("express");
    let app = express();
    let signupRoute = require("./routes/signup");
    
    app.listen(3000, function(req, res) {
      console.log("server started");
    });
    
    app.get("/",function(req,res){  
      console.log("home page called");
      res.send({message:"Thanks for calling home page"});
    });
    
    app.use("/signup",signupRoute);