Search⌘ K
AI Features

Creating the Backend

Explore setting up a backend server with Node.js and Express while connecting to MongoDB using environment variables. Learn to add middleware, create routes, and start the server. Understand how to handle JSON data and test basic API endpoints to ensure your backend works properly.

In this lesson, we'll start building our back-end server. The package.json file created previously has been provided below for reference:

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "mongodb": "^4.8.1"
  }
}
package.json

Adding express and cors middleware

Our backend uses the ES6 import statement. So before we start creating the backend, we need to add the import statement to our package.json.

C++
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1" },
...

This will use the import statements from ES6. Now, let’s create a new file server.js in the backend folder with the following code:

Javascript (babel-node)
import express from 'express'
import cors from 'cors'
import movies from './api/movies.route.js'
const app = express()
app.use(cors())
app.use(express.json())
app.use("/api/v1/movies", movies)
app.use('*', (req,res)=>{
res.status(404).json({error: "not found"})
})
export default app

Lines 1–3: First, we import the express and cors middleware. We also import movie.route.js (a separate file that we’ll create later to store our routes).

Line 5: We create the server.

Lines 6–7: For functionality, we attach the cors and express.json middleware to the Express server we created. The JSON parsing middleware express.json enables the server to read and accept JSON in a request’s body.

Lines 9–12: We specify the initial routes for our application.

Note: The general convention for API URLs is to begin ...