Node.js API Tutorial: Build a Read-Only Course Endpoint
- Get link
- X
- Other Apps
Web Development Learning Series — Part 7 of 10 · Advanced
A backend gives a web application a place to apply trusted rules and deliver data. In this lesson, create a small read-only course API using Node.js and its built-in HTTP module. Keeping the first endpoint simple makes routing and response behavior easier to understand.
Use a currently supported Node.js release. Save the code as server.mjs so its module syntax is explicit. This demonstration has no authentication, database, or write route; it is a local learning server.
Define the contract
A GET request to /api/courses returns a JSON array. An unknown path returns 404. An unsupported method on the course path returns 405. The client should not have to guess whether an error body is a successful list.
import { createServer } from 'node:http';
const courses = [
{ id: 'html', title: 'HTML Foundations', level: 'beginner' },
{ id: 'css', title: 'Responsive CSS', level: 'intermediate' }
];
function sendJson(res, status, data, extraHeaders = {}) {
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
...extraHeaders
});
res.end(JSON.stringify(data));
}
const server = createServer((req, res) => {
const path = new URL(req.url ?? '/', 'http://localhost').pathname;
if (path !== '/api/courses') {
return sendJson(res, 404, { error: 'Not found' });
}
if (req.method !== 'GET') {
return sendJson(res, 405, { error: 'Method not allowed' }, {
Allow: 'GET'
});
}
sendJson(res, 200, courses);
});
server.listen(3000, '127.0.0.1', () => {
console.log('API: http://127.0.0.1:3000/api/courses');
});Run and inspect it
In the project folder, run node server.mjs. Visit the printed URL. Then request /api/missing and check the response status in browser developer tools or an HTTP client. Stop the process when finished. Another service using port 3000 can cause a startup error; use an available port rather than assuming the application code is broken.
The loopback address keeps this example local. Changing the listening address or deploying the process changes who can reach it. Treat deployment as a separate task with its own configuration and operational checks.
Connect a frontend carefully
A page served on a different port has a different origin. The browser may block reading the API response unless the API has an appropriate CORS policy. For a simple learning project, serving the frontend and endpoint through the same origin avoids that additional setup.
If you add CORS later, permit only the origins and methods the application needs. CORS controls browser access to responses; it does not replace authentication or authorization on the server.
Where production changes the design
A real catalog may need pagination, a database, and a cache strategy. Write routes also need input limits, validation, authorization, and a decision about duplicate submissions. Never trust a hidden frontend button as a permission check. A caller can construct a request without using your interface.
Keep credentials in server-side configuration and out of committed code. Log enough information to diagnose a failed request, but avoid logging private data or secret tokens. Add health checks and graceful shutdown behavior when the deployment environment requires them.
Practice task
Add a documented level query parameter. Reject unknown values with a clear 400 response, rather than silently treating them as “all.” Test a matching level, an empty result, an invalid value, an unknown path, and an unsupported method. Write the expected status and response shape for each.
Continue your learning
Previous lesson: React State and Components: Build a Course Filter Without Extra State. Explore our web development series and the HTML multimedia project.
Reference: Official documentation for this lesson. Examples are learning exercises; adapt and test them for your own application.
- Get link
- X
- Other Apps
Comments
Post a Comment