app.get
- Node.js course
- Intermediate
- Lesson 26/116
- 5 min
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.
Practice 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 "/".
Starter code
// Import express and create app
// write here
// Respond with "Hello" to the "/" GET route
// write here
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(); });
});
});Sample 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(); });
});
});Expected output
Yanıt: Merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
app.get |
Defines a GET route |
req |
Carries the request |
res |
Lets you write the response |
res.send |
Sends the response |
2 Complete the res.send call
app.get("/", (req, res) => { res.____("Merhaba"); });
app.get("/", (req, res) => { res.send("Merhaba"); });
Explanation: res.send sends the response in Express.
3 What is the first parameter of app.get?
app.get("/yol", handler)- Handler fonksiyonu
- URL yolu Correct answer
- A port number
- An HTTP method
Explanation: The first parameter is the URL path.