Skip to content

Instantly share code, notes, and snippets.

@tjkhara
Last active November 11, 2020 13:38
Show Gist options
  • Select an option

  • Save tjkhara/367930f4ac6a553dd3341d73074c4398 to your computer and use it in GitHub Desktop.

Select an option

Save tjkhara/367930f4ac6a553dd3341d73074c4398 to your computer and use it in GitHub Desktop.
Complex App Note 1 - What is a router?

What is a router?

If you have an issue with

npm run watch

Do this

sudo pkill -f node

Create new file in root

router.js

javascript file communication

In router.js

console.log("I am executed immediately")
module.exports = "I am the export for the router file"

In app.js

below const app = express()

const router = require('./router')

Run the app and you will see that console.log line in the terminal.

The require function in node does two things:

  1. imports the file
  2. and returns what you set in module.exports in that file

in app.js below the const router try and log this variable to see what value you get

console.log(router)

You can export what you want in node. You can export an object also.

Try to return and object and log out its properties in app.js.

Clean out this demo code.

Learning routers

router.js

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

This gives us a sort of a mini application

router.get('/', function(req, res){
	res.render('home-guest')
})

module.exports = router

Back to app.js

Delete the app.get function

app.use('/',router)

Check app it should be working in browser

In router.js create an about url and try that use res.send() for simple test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment