// Step 1: Import the 'http' module
const http = require('http');
// Step 2: Create a server using the 'http' module
const server = http.createServer((req, res) => {
// Step 3: Check if the request URL is '/fetch'
if (req.url === '/fetch') {
// Step 4: Set the response headers
res.writeHead(200, {'Content-Type': 'text/plain'});
// Step 5: Use the 'fetch' function to make a request to an external resource
fetch('https://example.com')
.then(response => response.text())
.then(data => {
// Step 6: Send the fetched data as the response
res.end(data);
})
.catch(error => {
// Step 7: Handle errors, if any
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Internal Server Error');
});
} else {
// Step 8: If the request URL is not '/fetch', send a 404 response
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found');
}
});
// Step 9: Set the server to listen on port 3000
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});