1/* ====== create node.js server with express.js framework ====== */
2// dependencies
3const express = require("express");
4
5const app = express();
6
7app.get("/", (req, res) => {
8 res.send("This is home page.");
9});
10
11app.post("/", (req, res) => {
12 res.send("This is home page with post request.");
13});
14
15// PORT
16const PORT = 3000;
17
18app.listen(PORT, () => {
19 console.log(`Server is running on PORT: ${PORT}`);
20});
21
22
23// ======== Instructions ========
24// save this as index.js
25// you have to download and install node.js on your machine
26// open terminal or command prompt
27// type node index.js
28// find your server at http://localhost:3000
1// this is your code
2// ZDev1#4511 on discord if you want more help!
3// first you should install express in the terminal
4// `npm i express`.
5const express = require('express');
6const app = express();
7
8// route
9app.get('/', (req,res)=>{
10 // Sending This is the home page! in the page
11 res.send('This is the home page!');
12});
13
14// Listening to the port
15let PORT = 3000;
16app.listen(PORT)
17
18// FINISH!
1const express = require('express')
2const app = express()
3const port = 3000
4
5app.get('/', (req, res) => {
6 res.send('Hello World!')
7})
8
9app.listen(port, () => {
10 console.log(`Example app listening at http://localhost:${port}`)
11})
1const express = require('express');
2const app = express();
3const PORT = process.env.PORT || 3000;
4
5app.get('/', (req, res) => {
6 res.send('<h1>Some HTML</h1>');
7 res.send('<p>Even more HTML</p>');
8});
9
10app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
1const express = require('express')
2const app = express()
3const port = 3000
4
5app.get('/', (req, res) => res.send('Hello World!'))
6
7app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
8
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});
49
50// Running the server: node server.js