Node.js
app.get
Learn to define GET routes with app.get.
app.get
app.get(path, handler) defines a GET route. The first parameter is the URL path, the second is the request handler. The handler takes (req, res) and responds with res.send().
Example: app.get("/", (req, res) => { res.send("Hello"); });. This responds Hello to GET requests on the "/" path. res.send both sends the response and closes the connection; it is Express's simplified version of res.end. Express does routing automatically by path; you do not write if-else. Each route is defined with a separate app.get call.
Defining a route
To define a route you give a path and a handler. The path is a string (e.g. "/", "/about"). The handler is an arrow function: (req, res) => { ... }.
Example: app.get("/", (req, res) => res.send("Home"));. This responds Home to the root path. If the handler body is short you can omit the curly braces. To add multiple routes you make multiple app.get calls. Express matches the incoming request's path against routes in order; the first matching handler is called. If no match, Express returns 404.
Exercise Define a GET route
Import express and create app. Define a GET route with app.get("/", (req, res) => res.send("Hello")). The ready-made code below starts the server and sends a request to "/".
Show example solution
const express = require("express");
const app = express();
app.get("/", (req, res) => { res.send("Hello"); });
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});
Test yourself
-
Match each piece to its role
- app.get
- Defines a GET route
- req
- Carries the request
- res
- Lets you write the response
- res.send
- Sends the response
-
Complete the res.send call
app.get("/", (req, res) => { res.____("Merhaba"); });
Show answer
app.get("/", (req, res) => { res.send("Merhaba"); });
-
What is the first parameter of app.get?
app.get("/yol", handler)
- Handler fonksiyonu
- URL yolu
- A port number
- An HTTP method
Show answer
URL yolu — The first parameter is the URL path.
Next lesson: app.post