Prerequisites
Init project
touch index.jsyarn init -y
Install packages
yarn add express mongoose body-parser cors nodemon dotenv
- express: nodejs frameword help to create routing for app
- mongoose: help to create model for database
- body-parser: express middleware
- dotenv: Load environment variables from .env file
Connect database
- Goto Google and search "mongo atlas"
- Login with google
- Create a cluster
- Choose AWS and server Singapore => click Create Cluster
- Goto Database Access => Add New Database User => Filling all info => Add User
- Goto Network Access => Add IP Address
- Back to Cluster => click CONNECT => Choose "Connect your application"
- Add connect db to index.js
Initial Code for index.js
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import mongoose from 'mongoose';
import postsRouter from './src/routers/posts.js';
import crawlerRouter from './src/routers/crawler.js';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
const DATABASE_URL = process.env.DATABASE_URL;
app.use(bodyParser.json());
// Limit the data which the client will submit on server
app.use(bodyParser.urlencoded({ extended: true, limit: '30mb' }));
app.use(cors());
app.use('/posts', postsRouter);
app.use('/crawl-data', crawlerRouter);
mongoose.connect(DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true, useFindAndModify: false
}).then(() => {
console.log('Connected to database!');
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
}).catch((error) => {
console.log('Error', error);
})
Create .env file at root folder
PORT = 5000DATABASE_URL = 'url'
Run project
-
Add code below to package.json
"scripts": { "start": "nodemon index.js"}, - Run command line:
yarn start
Create project structure
mkdir srccd srcmkdir routersmkdir controllersmkdir models
Tags:
nodejs