simple express file server code example

Example 1: simple express server

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('

Some HTML

'); res.send('

Even more HTML

'); }); app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));

Example 2: app.use public

app.use(express.static('public'))
app.use(express.static('files'))

Example 3: 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());

//connecting to db
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('

Some HTML

'); res.send('

Even more HTML

'); }); app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));

Example 4: app.use public

express.static(root, [options])

Tags:

Misc Example