# Week 1 Study Plan: Express and HTTP from the Beginning

This guide explains the Week 1 class and the finished assignment in
`server.js`. Work through it in order; each section depends on the one before
it.

## What you should be able to do

By the end of the week, you should be able to:

1. explain the roles of a client, server, request, and response;
2. define GET and POST routes in Express;
3. find data in a query string, route parameters, form body, or JSON body;
4. return a response body and an appropriate HTTP status;
5. validate user input before using it;
6. use Postman or `curl` to test routes that a browser address bar cannot test.

## 1. Build the client/server mental model

A client asks for something. A server receives the request, runs code, and
sends a response.

```text
client -> HTTP request -> Express route -> HTTP response -> client
```

An HTTP request contains a method, a path, headers, and sometimes a body. For
example:

```text
GET /catalog?itemid=222
```

`GET` is the method. `/catalog` is the path. `itemid=222` is a query string.
The server matches the method and path to this code:

```js
app.get('/catalog', (req, res) => {
  // read the request and send a response
});
```

Checkpoint: explain why typing `/submitform` into a browser address bar cannot
test a POST route. The address bar sends GET, while the route expects POST.

## 2. Understand the Express setup

At the top of `server.js`, `express()` creates the application. Two middleware
functions prepare request bodies before routes use them:

```js
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
```

`express.urlencoded()` parses ordinary HTML form submissions.
`express.json()` parses JSON sent by Postman or another program. After parsing,
the submitted values are available in `req.body`.

At the bottom, `app.listen(3000)` starts the server. Port 3000 is one numbered
door on the computer. The full local address is `http://localhost:3000`.

Exercise:

1. Run `npm start`.
2. Visit `/` and `/about`.
3. Change one response string, save, and observe Node's watch mode restart the
   server.
4. Restore the response before continuing.

## 3. Learn the four places this assignment receives input

### Query strings

`GET /catalog?itemid=222` places `222` in `req.query.itemid`. Query strings are
good for searches and filters because they do not identify a different route.

The code verifies that `itemid` is one string, is not blank, and converts to a
number. A bad value returns status 400 and the exact required message.

### Route parameters

The colons in this route mark changing path segments:

```js
app.get('/play/artist/:artist/song/:song', ...)
```

For `/play/artist/Radiohead/song/Creep`, Express creates:

```js
req.params.artist === 'Radiohead'
req.params.song === 'Creep'
```

URL encoding turns `%20` into a space, so `The%20Clash` reaches the handler as
`The Clash`.

### HTML form bodies

`GET /getform` returns HTML containing a form. The form's `action` and `method`
tell the browser to send a POST to `/submitform`. Each input's `name` becomes a
key in `req.body`:

```js
const { address, city, zipcode } = req.body;
```

The ZIP code stays a string. That preserves a leading zero such as `01234`.

### JSON bodies

`POST /tracks` receives JSON. Postman must send `Content-Type:
application/json`, and the server needs `express.json()` before the route.
The route destructures the four fields from `req.body` and returns a JSON
object with the added track and a timestamp.

Checkpoint: for each assignment route, identify whether its inputs come from
`req.query`, `req.params`, or `req.body`.

## 4. Understand validation and status codes

The catalog route returns `400 Bad Request` when `itemid` is not numeric. The
track route also returns 400 when `artist` or `title` is missing, is not a
string, or contains only spaces.

The pattern is:

```js
if (inputIsInvalid) {
  res.status(400).send('helpful message');
  return;
}
```

The `return` matters. Once the server sends an error response, the handler
must stop. Otherwise it may try to send a second response.

Useful first-week statuses:

- 200: the request succeeded;
- 400: the client supplied unusable input;
- 404: no route matches the requested method and path;
- 500: application code failed unexpectedly.

Exercise: test `/catalog` with `222`, `3`, `xyz`, a blank value, and no
`itemid` key. Predict the status and body before sending each request.

## 5. Walk through every assignment route

| Route | Input source | Main transformation |
| --- | --- | --- |
| `GET /catalog` | query `itemid` | validate number and place it in a sentence |
| `GET /play/artist/:artist/song/:song` | two route parameters | place both decoded values in a sentence |
| `GET /getform` | none | return an address form |
| `POST /submitform` | form body | combine address, city, and ZIP code |
| `GET /browse/:category` | route parameter + query | combine category and keywords |
| `GET /hithere` | query `name` | create a greeting |
| `POST /tracks` | JSON body | validate and return a structured JSON result |
| `GET /products/:department/:category` | two route parameters + query | turn comma-separated keywords into `AND` terms |

The product search calls `split(',')` to make an array and `join(' AND ')` to
make the required display string. For example:

```text
lcd,smart,sony -> ['lcd', 'smart', 'sony'] -> lcd AND smart AND sony
```

The track response uses `new Date().toISOString()`. The exact time changes on
every request, but the ISO format stays predictable.

## 6. Suggested study session

### First 20 minutes: HTTP basics

- Draw one request and response.
- Label method, path, query string, headers, body, status, and response body.
- Explain GET versus POST aloud.

### Next 25 minutes: trace the code

- Read `server.js` from top to bottom.
- For every route, write down where its inputs live.
- Cover the handler and predict its response from only the request URL/body.

### Next 25 minutes: send requests

- Create a Week 1 Postman folder.
- Save one request for each route.
- Test successful and invalid catalog/track cases.
- Confirm the status as well as the visible body.

### Final 20 minutes: change and restore

- Add one temporary route parameter to a practice route.
- Add one temporary query-string filter.
- Add one validation check that returns 400.
- Test each change, then restore the submitted assignment code.

## Final self-check

You are ready for Week 2 when you can answer these without opening the notes:

1. What is the difference between a method and a path?
2. Where do query parameters, route parameters, and submitted bodies appear
   on `req`?
3. Why must body-parsing middleware come before the routes?
4. Why does an error branch send a response and then return?
5. What makes an input problem a 400 instead of a 500?
6. Why is Postman useful for POST requests?

Run the assignment with:

```bash
npm install
npm start
```
