1// npm init
2// npm i express
3
4const express = require('express');
5const server = express();
6
7const PORT = 3000;
8
9// Body parser
10server.use(express.json());
11
12// Homme page
13server.get('/', (req, res) => {
14 return res.send("<h1 style='text-align: center;'>Hello,<br />from the Express.js server!</h1>");
15})
16
17// About page
18server.get('/about', (req, res) => {
19 return res.send('<h2 style="text-align:center">About us</h2>');
20})
21
22// 404 page
23server.use((req, res, next) =>{
24 res.status(404);
25
26 // respond with html page
27 if (req.accepts('html')) {
28 res.sendFile(__dirname + '/error404.html');
29 return;
30 }
31 // respond with json
32 else if (req.accepts('json')){
33 res.send({
34 status: 404,
35 error: 'Not found'
36 });
37 return;
38 }
39 // respond with text
40 else {
41 res.type('txt').send('Error 404 - Not found');
42 }
43});
44
45// Listening to the port
46server.listen(PORT, () => {
47 console.log(`Server is running on port ${PORT}`);
48});
1const express = require('express')const app = express() app.get('/', function (req, res) { res.send('Hello World')}) app.listen(3000)
1// create directory
2
3//npm init -y
4//npm i express --save
5
6//create public directory
7//create server.js
8
9// <---- In the server js file --->
10
11'use strict';
12
13const express = require('express');
14const app = express();
15app.use(express.static('public'));// to connect with frontend html
16app.use(express.json());//body parse
17
18app.get('/', function(req,res){
19 res.send('This is the Homepage');
20 //res.sendFile('index.html');
21});
22
23app.listen(3000);
24