Node.js Basics: JavaScript Outside the Browser
Your First HTTP Server
In this lesson you will
- Create a server with the http module
- Respond with JSON and the right status codes for different routes
- Test a server from code using fetch
Introduction
A web server listens for requests and sends back responses. Node includes everything you need to build one, with no packages. Understanding this foundation makes frameworks such as Express much easier to understand.
The simplest server
What each part does:
createServertakes a function that runs for every request.reqdescribes the request:req.method(such as GET) andreq.url(the path).resis how you answer:writeHeadsets the status code and headers, andendsends the body and finishes the response.server.listen(3000)starts listening on port 3000. Openhttp://localhost:3000/helloin a browser.
Always send a response for every path, or the visitor waits forever.
Quick quiz
What does the function passed to createServer receive?
Testing it from code
Node includes the fetch function, the same one browsers have. Here is a complete script that starts the server on any free port (port 0), calls it and stops. The outputs come from a real run:
200 { message: 'Hello' }
404 { error: 'Not found' }Using port 0 asks the operating system for a free port, which is handy in tests.
Status codes and headers
- 200 OK, 201 Created, 204 No Content
- 400 Bad Request (the client sent something wrong), 404 Not Found
- 500 Internal Server Error (something broke on your side)
Set the content-type header so clients know how to read the body, such as application/json or text/html.
Reading a request body
The body arrives in pieces, so you collect them:
Then parse it with JSON.parse, inside a try block, because clients can send invalid JSON. Limit the size of bodies you accept, so one huge request cannot use all your memory.
Why use a framework?
Handling routes with if statements, parsing bodies, validation, errors and security headers by hand gets repetitive. Frameworks such as Express handle the routine parts. You will use Express in the intermediate course, and you will understand what it does for you.
Staying safe
- Never send raw error details or stack traces to users in production.
- Validate everything that comes from a request.
- Do not serve files from user-supplied paths without strict checks.
- Do not expose a development server to the internet.
Try it yourself
Add a /time route that returns the current time as JSON, and a /echo route that returns the query string you send. Test both with fetch.
Summary
createServerruns your function for each request, and you answer with a status, headers and a body.- Return JSON with the right status codes, and always respond for unknown paths.
- Test servers with
fetch, and use a framework when routing and validation grow.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading