Express
Web Technology
Rourab Paul, Subin Sahayam, Assistant Professor,
Department of Computer Science and Engineering
Shiv Nadar University
Express
K1
Express
K2
Express
K3
Express
K3
// Import Express
const express = require('express');
// Create an Express app
const app = express();
// Define a route
app.get('/', (req, res) => {
res.send('Hello World! My first Express app!');
});
// Start the server on port 3000
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
// Import Node.js HTTP module
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// Check the requested URL
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Hello World! My first Node.js app!');
} else {
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.end('Page Not Found');
}
});
// Start the server on port 3000
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Express
K3
Express
K3
const express = require('express');
const app = express();
// Home page
app.get('/', (req, res) => {
res.send('<h1>Welcome to my website!</h1>');
});
// About page
app.get('/about', (req, res) => {
res.send('<h1>About Us</h1><p>This is my first Express app!</p>');
});
// Contact page with dynamic content
app.get('/contact/:name', (req, res) => {
const name = req.params.name;
res.send(`<h1>Contact: ${name}</h1>`);
});
// Start server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const pathname = url.parse(req.url).pathname;
// Home page
if (pathname === '/') {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end('<h1>Welcome to my website!</h1>');
}
else if (pathname === '/about') {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(
'<h1>About Us</h1>' +
'<p>This is my first Node.js app!</p>'
);
}
else if (pathname.startsWith('/contact/')) {
// Extract name from URL
const name = pathname.split('/')[2];
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(`<h1>Contact: ${name}</h1>`);
}
else {
res.writeHead(404, {
'Content-Type': 'text/html'
});
res.end('<h1>404 - Page Not Found</h1>');
}
});
// Start server
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Express
K3
Middleware
K1
Middleware
K2
Middleware
K2
Middleware
K2
References
THANK YOU