how to run express server code example
Example 1: 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 2: how to make an express server
const express = require('express');
const app = express();
app.get('/', (req,res)=>{
res.send('This is the home page!');
});
let PORT = 3000;
app.listen(PORT)
Example 3: simple express 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 4: simple express server
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
try {
mongoose.connect('mongodb://localhost/YOUR_DB_NAME', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}, () =>
console.log("connected"));
} catch (error) {
console.log("could not connect");
}
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: create express server local
'use strict';
const express = require('express');
const app = express();
app.use(express.static('public'));
app.use(express.json());
app.get('/', function(req,res){
res.send('This is the Homepage');
});
app.listen(3000);