nodejs create server basic 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: create node js server
import express from 'express';
const server = express();
const port = 8080;
server.get('/', (req, res) => {
return res.send('Hello, Express.js!');
})
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});