web server node js code example
Example 1: how to create node js server
const http = require("http");
const PORT = 3000;
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.write("This is home page.");
res.end();
} else if (req.url === "/about" && req.method === "GET") {
res.write("This is about page.");
res.end();
} else {
res.write("Not Found!");
res.end();
}
});
server.listen(PORT);
console.log(`Server is running on PORT: ${PORT}`);
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("This is home page.");
});
app.post("/", (req, res) => {
res.send("This is home page with post request.");
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on PORT: ${PORT}`);
});
Example 2: node js server
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
Example 3: how to create a server in node js
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);