1

Greeting everyone, I am learning fullstack javascript development via video tutorials i am new to development , requesting you to help me!!

My application have app.js file code is

const express = require("express")
const app = express()
const router = require("./router")
app.set("views", "views")
app.set("view engine", "ejs")
app.use(express.static("public"))
app.get("/", router)
app.listen(3000)

Router.js file code is

    const express = require("express")
    const router = express.Router()
    const userController = require("./controllers/userController.js")
    router.get("/", userController.home)
    router.post("/register", userController.register)
    module.exports = router

userController.js file in controllers folder code is

exports.register = function(req, res){
    res.send("Thanks for trying to register")
}
exports.home = function(request, response){
    response.render("home-guest")
}

I am using ejs and home.ejs file is having html form when try to submit a form eg

<form action="/register" method="POST" id="registration-form">
<div class="form-group">
          <label for="username-register" class="text-muted mb-1"><small>Username</small></label>
          <input name="username" id="username-register" class="form-control" type="text" placeholder="Pick a username" autocomplete="off">
        </div>
    </form>

Why i am getting an error - Cannot POST /register

Rohan Saka
  • 29
  • 1
  • 6

1 Answers1

1

You're only using your router for GET requests here:

app.get("/", router)

That's why the POSTs are not hitting your router at all.

You can mount it to handle all methods istead, via app.use():

app.use("/", router)

Read more about the difference between the two here: Difference between app.use and app.get in express.js

shkaper
  • 4,689
  • 1
  • 22
  • 35
  • nice worked thanks!!!!!!! :) but will be more thanfull if you can explain a bit more..as i am a beginner – Rohan Saka Mar 07 '20 at 18:09
  • @RohanSaka sure. Basically, `app.get('/path', handlerFunction)` tells express to run `handlerFunction` whenever `GET` requests hit the server on `/path` path. In your app, you're running a Router that encapsulates route handling logic, including which methods to handle, therefore you need a more generic `app.use()` for that. I've added some more helpful links to my answer, hope that helps. – shkaper Mar 07 '20 at 20:17
  • much appreciated!!! shkaper. You again put me on a path to development .. thanks a lot for clarifying my basics its a great help:) – Rohan Saka Mar 08 '20 at 18:21