Init NodeJS backend

Init NodeJS backend

Written by Константин Савченко | Published a month ago

1) run

nmp init -y


2) install modules

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "mongoose": "^5.10.7",
    "morgan": "^1.10.0",
    "nodemon": "^2.0.4"
  }
}


3) create server.js and fill it

const express = require('express')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const cors = require('cors')
require('dotenv').config()

// app
const app = express()

// middlewares
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(cookieParser())

// cors
app.use(cors())

// routes
app.get('/api', (req, res) => {
    res.json({time: Date().toString()})
})

// port
const port = process.env.PORT || 8000

app.listen(port, () => {
    console.log(`Server is running on port ${port}`)
})


For start server run

npm start

RELATED BLOGS