Example 1: express.js server
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: express hello world
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: expressjs server
const express = require('express');
const server = express();
const PORT = 3000;
server.use(express.json());
server.get('/', (req, res) => {
return res.send("<h1 style='text-align: center;'>Hello,<br />from the Express.js server!</h1>");
})
server.get('/about', (req, res) => {
return res.send('<h2 style="text-align:center">About us</h2>');
})
server.use((req, res, next) =>{
res.status(404);
if (req.accepts('html')) {
res.sendFile(__dirname + '/error404.html');
return;
}
else if (req.accepts('json')){
res.send({
status: 404,
error: 'Not found'
});
return;
}
else {
res.type('txt').send('Error 404 - Not found');
}
});
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Example 4: 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 5: require express server.js
const express = require('express')const app = express() app.get('/', function (req, res) { res.send('Hello World')}) app.listen(3000)
Example 6: js express server
const http = require('http')
const express = require('express')
const app = express()
const server = http.Server(app)
app.set('port', 8888)
server.listen(8888)
app.get('/', (req, res) => {
res.json({teste: true})
})