express port code example
Example 1: express.js server
/* ====== create node.js server with express.js framework ====== */
// dependencies
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.");
});
// PORT
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on PORT: ${PORT}`);
});
// ======== Instructions ========
// save this as index.js
// you have to download and install node.js on your machine
// open terminal or command prompt
// type node index.js
// find your server at http://localhost:3000
Example 2: express js server
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('<h1>Some HTML</h1>');
res.send('<p>Even more HTML</p>');
});
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
Example 3: require express server.js
const express = require('express')const app = express() app.get('/', function (req, res) { res.send('Hello World')}) app.listen(3000)
Example 4: express get port from request
const proxyHost = req.headers["x-forwarded-host"];
const host ? proxyHost : req.headers.host;