skip to Main Content

I just started learning back-end development so this may be a very simple mistake. I got an error "Cannot Get /" after entering localhost:3000 into my browser. Here is my index.js file and a router module. They are both in the same folder, ‘basic-node-site’:

const express = require("express")
const router = express.Router()
const path = require('path')

router.get("/", function (req,res){
    res.sendFile(path.join(__dirname, '/index.html'))
})

router.get("/contact-me", function (req,res){
    res.sendFile(path.join(__dirname, '/contact-me.html'))
})

router.get("/about", function (req,res){
    res.sendFile(path.join(__dirname, '/about.html'))
})

module.exports = router
const router = require('./route-module.js')
const express = require("express")
const app = express()
const port = 3000
app.use(express.static('basic-node-site'))

app.use("/route-module", router)



app.listen(3000, function(){
    console.log("listening on port 3000")
})

I tried multiple different pathnames just in case I was misunderstanding something about how they were formatted. Every time I got "cannot get /" where I expected to get the HTML file displayed in the browser.

2

Answers


  1. The path is not accurate in index.js file, can you change

    app.use("/route-module", router) 
    

    into below

    app.use("/", router)
    
    Login or Signup to reply.
  2. You don’t go to the public folder. The index.html file and other html files are in public folder right?

    You should do this:

    router.get("/", function (req, res) {
      res.sendFile(path.join(__dirname, 'public/index.html'))
    });
    
    router.get("/contact-me", function (req, res) {
      res.sendFile(path.join(__dirname, 'public/contact-me.html'))
    });
    
    router.get("/about", function (req, res) {
      res.sendFile(path.join(__dirname, 'public/about.html'))
    });
    

    Let me know if it works for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search