0
0
ExpressHow-ToBeginner · 3 min read

How to Create Routes in Express: Simple Guide

In Express, you create a route using app.METHOD(path, handler), where METHOD is an HTTP method like get or post. The path is the URL pattern, and the handler is a function that runs when the route is accessed.
📐

Syntax

The basic syntax to create a route in Express is:

  • app: Your Express application instance.
  • METHOD: HTTP method like get, post, put, delete.
  • path: The URL path string or pattern.
  • handler: A function with request and response parameters that defines what happens when the route is called.
javascript
app.METHOD(path, (req, res) => {
  // code to handle the request
});
💻

Example

This example shows how to create a simple GET route at /hello that sends a greeting message to the browser.

javascript
import express from 'express';
const app = express();
const port = 3000;

app.get('/hello', (req, res) => {
  res.send('Hello, welcome to Express routing!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Output
Server running at http://localhost:3000 When you visit http://localhost:3000/hello in a browser, it shows: Hello, welcome to Express routing!
⚠️

Common Pitfalls

Common mistakes when creating routes include:

  • Using app.get but expecting to handle POST requests.
  • Forgetting to call res.send() or res.end(), causing the request to hang.
  • Not specifying the correct path, leading to routes not matching requests.
  • Placing app.listen() before defining routes, which can cause routes to not work as expected.
javascript
/* Wrong: Using GET but expecting POST data */
app.get('/submit', (req, res) => {
  res.send('This will not handle POST requests');
});

/* Right: Use POST method for form submissions */
app.post('/submit', (req, res) => {
  res.send('POST request handled correctly');
});
📊

Quick Reference

Here is a quick reference for common HTTP methods used in Express routes:

HTTP MethodDescription
GETRetrieve data from the server
POSTSend data to the server to create something
PUTUpdate existing data on the server
DELETERemove data from the server
PATCHPartially update data on the server

Key Takeaways

Use app.METHOD(path, handler) to create routes in Express.
Match the HTTP method to the type of request you want to handle.
Always send a response with res.send() or similar to avoid hanging requests.
Define routes before calling app.listen() to ensure they work.
Use clear and correct paths to match client requests.