Simple HTTP servers with Node and Express-
Two Lines
import express from 'express'
const app = express().get('/', req => res.send("Hey world")).listen(3000, () => console.log("Listening on port 3000"))Four lines
import express from 'express'
const app = express()
app.get('/', req => res.send("Hey world"))
app.listen(3000, () => console.log("Listening on port 3000"))Don’t forget your packages and package.json:
npm init -y
npm install expressModify your package.json so that it has
"type": "module"Otherwise just use the require syntax to import express:
const express = require('express')Node app without express
Express is very nice, but if you didn’t even want to use npm at all, you can do all of this using just Node.
import http from 'http';
http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.end('Hey world');
} else {
res.statusCode = 404;
res.end('Not Found');
}
}).listen(3000, () => console.log('Listening on port 3000'));