Intro
So we installed NodeJS on our machine.
We also learned how to create a simple server using express.
Now we want to learn how to add routes to our express server.
Reuse our simple server from the last article
- Open your terminal
- Create a file named
index.js
:
touch index.js
- Add this JavaScript code into it:
const express = require("express");
const app = express();
const PORT = 8080;
app.get("/", (request, response) => {
response.send("Hello World");
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
Note: This is our starting point, we have one working route.
I updated req
to request
& res
to response
to increase readability.
Basic Routing
What is Routing?
Every time a client (e.g. the user's browser) requests an app's endpoint, the server has to respond.
The client sends a specific HTTP request method, e.g. GET
, and a path, e.g. /
.
To respond to this request, our express app needs to know how to respond.
Example from above:
app.get("/", (request, response) => {
response.send("Hello World");
});
When our express app gets a get
-request
to /
, it send
s a response
of Hello World
.
We can see all relevant words immediately.
Every route in express has the same syntax:
app.METHOD(PATH, HANDLER);
- METHOD: Which HTTP request method was sent by the client? (e.g.
GET
) - PATH: Which path does the client request? (e.g.
/
,/account
,/dashboard
) - HANDLER: How should the app respond to the request? (e.g. send data back, redirect, log something)
Add a new route
- Add a new route to
/welcome
for aget
-request:
const express = require("express");
const app = express();
const PORT = 8080;
app.get("/", (request, response) => {
response.send("Hello World");
});
app.get("/welcome", (request, response) => {
response.send("Welcome!");
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
Run it from the terminal
- Run it:
node index.js
- Console Result:
Server running at: http://localhost:8080/
Visit: http://localhost:8080/welcome
- Client Result:
Further Reading
Your Task
- Create a basic route, that handles a
GET
-request to/dashboard
, thatresponds
withThis is your dashboard
- If you want to get some feedback, I invite you to share your code in the comments (beginner) or on Github (advanced)