task 6

PHOTO EMBED

Wed Apr 23 2025 01:42:23 GMT+0000 (Coordinated Universal Time)

Saved by @cciot

🔹 Part 1: Create a basic HTTP server (no Express)

This server listens on port 3000 and serves HTML, plain text, and JSON based on the request URL.

// httpServer.js
const http = require('http');
const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>Welcome to the Home Page</h1>');
  } else if (req.url === '/text') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('This is plain text');
  } else if (req.url === '/json') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Hello, this is JSON response!' }));
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('404 Not Found');
  }
});

server.listen(3000, () => {
  console.log('HTTP server running at http://localhost:3000');
});

🔹 Part 2: Create an Express server
This server also listens on port 3000 and uses Express with multiple endpoints.
// expressServer.js
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
  res.send('<h1>Welcome to the Express Home Page</h1>');
});

app.get('/text', (req, res) => {
  res.type('text').send('This is a plain text response');
});

app.get('/json', (req, res) => {
  res.json({ message: 'Hello from Express JSON endpoint!' });
});

app.get('/html', (req, res) => {
  res.send(`
    <html>
      <head><title>Express HTML</title></head>
      <body><h1>This is HTML served with Express</h1></body>
    </html>
  `);
});

app.use((req, res) => {
  res.status(404).send('404 Not Found');
});

app.listen(PORT, () => {
  console.log(`Express server running at http://localhost:${PORT}`);
});

✅ Run the Servers
To run either server:
node httpServer.js     # for native HTTP server
# or
node expressServer.js  # for Express server

Make sure to install Express for the second part if you haven’t:
npm install express
content_copyCOPY