We are going to build a blog api with node and express, the app will contain the users model and blogs model , the app will be simple and has no authentication.
Requirements
β
Packages
Now we can start to build the project.
Step 1: Create a project folder
mkdir blog_api
cd blog_api
Initialize the Project
npm init --y
You will be asked some questions, you can answer them or skip the questions by pressing ENTER, after this step you will have a package.json file into your folder.
Step 2: Install dependencies
npm install express express-validator dotenv cors mongodb mongoose morgan
Also, we need to add the dev dependencies
npm install --save-dev nodemon
Dev dependencies are those packages in the package. json file that you need only for project development purposes.
const express = require("express");
var cors = require("cors");
const bodyParser = require("body-parser");
require("dotenv").config(); // Allows us to access variables in .env file
// Initialize the app
const app = express();
const port = process.env.PORT || 8000;
app.use(cors()); // Use cors
app.use(bodyParser.json({ limit: "25mb" }));
app.get("/", (req, res) => res.send("Express + Testing")); // Simple route
app.listen(port, () => { // Start the server
console.log(`π Server is running at https://localhost:${port}`);
});
This is a simple express server which will return the Express + Testing
Step 4: Modify the package.json
In package.json inside the scripts add the code "start": "nodemon server.js" .
This will refresh your server each time you make changes.
"scripts": {
"start": "nodemon server.js"
},
Now you can run npm start in your terminal to start your app.
If you visit http://localhost:8000/ in your browser, the app will return Express + Testing
Step 5: Project structure
If you are using mac , linux or bash Run the command below in your terminal.