setup node server with express code example

Example 1: how to make an express server

// this is your code
// ZDev1#4511 on discord if you want more help!
// first you should install express in the terminal
// `npm i express`.
const express = require('express');
const app = express();

// route
app.get('/', (req,res)=>{
  // Sending This is the home page! in the page
  res.send('This is the home page!');
});

// Listening to the port
let PORT = 3000;
app.listen(PORT)

// FINISH!

Example 2: create server with express js

// npm init
// npm i express

const express = require('express');
const server = express();

const PORT = 3000;

// Body parser
server.use(express.json());

// Homme page
server.get('/', (req, res) => {
  return res.send("<h1 style='text-align: center;'>Hello,<br />from the Express.js server!</h1>");
})

// About page
server.get('/about', (req, res) => {
  return res.send('<h2 style="text-align:center">About us</h2>');
})

// 404 page
server.use((req, res, next) =>{
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.sendFile(__dirname + '/error404.html');
    return;
  }
  // respond with json
  else if (req.accepts('json')){
    res.send({
      status: 404,
      error: 'Not found'
    });
    return;
  }
  // respond with text
  else {
    res.type('txt').send('Error 404 - Not found');
  }
});

// Listening to the port
server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Example 3: setup node js express basic setup

npm init -y
npm i express

Example 4: how to use http in development mode for nodejs

var   fs = require("fs"),
      http = require("https");

var privateKey = fs.readFileSync('sslcert/server.key').toString();
var certificate = fs.readFileSync('sslcert/server.crt').toString();

var credentials = {key: privateKey, cert: certificate};

var server = http.createServer(credentials,function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
});

server.listen(8000);