HTTP Server and fetch Together
Node 18 and newer include fetch. This example starts a server on a free port and calls it, all in one script.
Example
const http = require('node:http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ path: req.url, method: req.method }));
});
server.listen(0, async () => {
const { port } = server.address();
const r = await fetch(`http://localhost:${port}/hello`);
console.log(r.status, await r.json());
server.close();
});Result
200 { path: '/hello', method: 'GET' }Exercise
Listen on a random port.
server.listen()
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.