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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

nice worked thanks!!!!!!! :) but will be more thanfull if you can explain a bit more..as i am a beginner
@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.
much appreciated!!! shkaper. You again put me on a path to development .. thanks a lot for clarifying my basics its a great help:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.