simple web server with node.js code example

Example 1: create server with node js

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

const PORT = 3000;

// Homme page
server.get('/', (req, res) => {
  return res.send("

Hello,
from the Express.js server!

"); }) // About page server.get('/about', (req, res) => { return res.send('

About us

'); }) // 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'); } }); server.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });

Example 2: how to create a server in node js

// code by VARSHITH REDDY SATTI
// to create a server in node.js you should.
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("write html code to display you test")
  res.end();
}).listen(8080);
// save this as httpServer.js
// run this by typing node httpServer.js in the command line
// to acess your server got to http://localhost:8080

Tags:

Misc Example