- Create package.json file
npm init
- Install express and nodemon (nodemon serves like a live server for node.js)
npm install express nodemon
- Add code to run npm, in package.json file and inside "scripts" add the following code
"start": "nodemon app.js"
- Create app.js file
- Connect to MongoDB using mongoose
npm install mongoose
- Install dotenv package to hide information
npm install dotenv
Then, create a file called ".env" and put the hidden information in under a variable name
- Go to mlab.com and SignUp for MongoDB account
- After that just choose a service provider (AWS, GCP), your choice
- Choose the Connect button on the left side of the screen
- You will need to setup your UserId and password.
- After that, choose the Connect your application option
- Paste the link they give into the code
- Replace the <password> with your password and give a name (your choice) for the <dbname>
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("Connected to DB");
}
);
Using express.Router to set up routes and import that into the main Javascript file using app.use (aka. middlewares)
- Create a model file Post.js in modules folder to setup an outline for the post
- Import the Post model into the posts.js file in routes to start creating, reading, deleting, or updating the posts
- Install cors:
npm install cors
- Create a middleware in the main js file to inable cors
const cors = require("cors");
app.use(cors());
- Clone the Project
- Install the packages:
npm install
- Create a new Database (mentioned above)
- Change the code to connect to the database (mentioned above)
- Run the server:
nodemon app.js
- Create the PostMan account the try requesting the api from your local host
- Fetch the data from other javascript file
Tutorial Video: Build A Restful Api With Node.js Express & MongoDB | Rest Api Tutorial