HTTP Servers & APIs — Series 2

Preview — 3 of 10 questions

Assume a client sends POST /api/items with header Content-Type: application/json. What is logged inside the handler, and what does the client ultimately receive?

javascript
const http = require('http');

const server = http.createServer((req, res) => {
  console.log(req.method);
  console.log(req.headers['content-type']);
  res.setHeader('X-Powered-By', 'MyApp');
  res.statusCode = 201;
  res.end(JSON.stringify({ ok: true }));
});
A"POST", "application/json"; client receives status 200, since res.statusCode must be set before any headers.
B"post", "application/json"; client receives status 201.
C"POST", "application/json"; client receives status 201 with body {"ok":true} and an X-Powered-By: MyApp header.
D"POST", undefined — since Content-Type (capitalized) doesn't match content-type.

A client requests GET /search?name=alice&page=2. What does the server respond with?

javascript
const http = require('http');

const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const name = url.searchParams.get('name');
  const page = url.searchParams.get('page');

  res.end(`name=${name}, page=${page}`);
});
A"name=undefined, page=undefined"
B"name=null, page=null"
CTypeError: req.url is not a valid URL
D"name=alice, page=2"

What does this respond with, and what is the purpose of express.Router() here?

javascript
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => res.send('List items'));
router.get('/:id', (req, res) => res.send(`Item ${req.params.id}`));

const app = express();
app.use('/api/items', router);

// Request: GET /api/items/42
A"Item 42" — express.Router() creates a modular, mountable set of route handlers, letting related routes be organized separately and mounted onto the app at a specific base path.
B"List items" — since the router always matches its first route regardless of the actual path.
C404 Not Found — since routers cannot be mounted with app.use().
D"Item 42" — but express.Router() is only usable for GET requests, never POST/PUT/DELETE.

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.