TASK 6: Working with http

PHOTO EMBED

Tue Apr 22 2025 19:47:28 GMT+0000 (Coordinated Universal Time)

Saved by @signup

https://chatgpt.com/share/6806ee63-d908-800e-96ea-a6b4640389c6


//1. Create a http server listening request at port 3000. Process the request to provide different type of resources as response. (HTML, TEXT, JSON, etc.).

//server.js


javascript
Copy
Edit
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({ name: 'Node.js', type: 'runtime' }));
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 - Page Not Found');
    }
});

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




//2. Create express server listening request at port 3000. Add different endpoints to provide access to the resources.

//app.js


javascript
Copy
Edit
const express = require('express');
const app = express();

// HTML response
app.get('/', (req, res) => {
    res.send('<h1>Welcome to Express Server</h1>');
});

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

// JSON response
app.get('/json', (req, res) => {
    res.json({ language: 'JavaScript', framework: 'Express' });
});

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

https://chatgpt.com/share/6806ee63-d908-800e-96ea-a6b4640389c6