Lecture note on GET vs POST, when to use each, and provides Express.js examples for handling URL parameters, query strings, and POST bodies.
📘 Lecture Note: GET vs POST & Extracting URL Parameters in Express.js
1. What is an HTTP Method?
When clients (browsers, curl, APIs) talk to a web server, they use HTTP methods. The two most common in web development are: GET – ask the server for information. POST – send data to the server (usually to create something). 2. GET Requests
Parameters go in the URL. Safe to bookmark and cache. Visible in the browser address bar. Should not modify server state. Example URL with query string:
/search?term=icecream&limit=10
Express handler:
app.get('/search', (req, res) => {
const term = req.query.term; // "icecream"
const limit = req.query.limit; // "10"
res.send(`Searching for ${term}, limit = ${limit}`);
});
3. POST Requests
Purpose: Submit data (create, update, send forms). Data goes in the request body, not the URL. Not visible in the browser bar. Common for forms, logins, API writes. HTML form example (POST):
<form action="/signup" method="POST">
<input name="username" placeholder="Username" />
<input name="password" type="password" placeholder="Password" />
<button type="submit">Sign Up</button>
</form>
Express handler:
app.post('/signup', (req, res) => {
const username = req.body.username; // parsed by express.urlencoded()
const password = req.body.password;
res.send(`User created: ${username}`);
});
⚓ Note: To handle form or JSON bodies in Express, you must use middleware:
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
4. Route Parameters (/path/:variable)
Route parameters are part of the URL itself, not query strings. /hello/Amy
Express handler:
app.get('/hello/:name', (req, res) => {
const name = req.params.name; // "Amy"
res.send(`Hello, ${name}!`);
});
5. Comparing GET vs POST
6. Testing with curl
GET with query string
curl "http://localhost:3000/search?term=icecream&limit=10"
GET with route param
curl "http://localhost:3000/hello/Amy"
POST with form data
curl -X POST http://localhost:3000/signup -d "username=kirk&password=enterprise"
POST with JSON
curl -X POST http://localhost:3000/signup \
-H "Content-Type: application/json" \
-d '{"username":"spock","password":"logical"}'
7. Deliverables (Cadet Checklist)
I can explain the difference between GET and POST. I can extract query params (req.query). I can extract route params (req.params). I can extract POST body data (req.body). I tested with curl and saw expected output. ⚓ Commander's Intent:
Cadets leave this lecture able to:
Explain when to use GET vs POST. Build Express routes using params, queries, and body. Test routes using curl or browser. Later we will see examples with:
GET /calculator?x=10&y=5&op=add POST /calculator (with JSON { "x":10, "y":5, "op":"add" })
so they practice GET vs POST side-by-side?