Basic Routing
Where to, Scotty?
Section titled “Where to, Scotty?”In Express, Routing is our GPS. It determines how our application responds to a client request for a particular endpoint.
The structure is simple: app.METHOD(PATH, HANDLER).
- app: The instance of express.
- METHOD: The HTTP request method (get, post, put, delete, etc.).
- PATH: A path on the server.
- HANDLER: The function executed when the route is matched.
The Interchange
Section titled “The Interchange”
Fig 1: The Routing Logic. Follow the colors or get lost in traffic.
Our First Route
Section titled “Our First Route”// The "GET" Lane -> Retrieve Info// Path: Root ("/")app.get('/', (req, res) => { res.send('Engine Online. Hello Express!');});
// Path: /thingsapp.get('/things', (req, res) => { res.send('Here is the list of things you asked for.');});Solo Warning: Express matches routes in the order they are defined. First match wins. If you have two routes for
/things, the second one will never be reached. Traffic doesn’t loop back.
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Basic Express Routing - Demo Repo