- Notifications
You must be signed in to change notification settings - Fork0
Turzoxpress/Node_REST_API_Server_Express_MongoDB
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
In this tutorial we will create aNode.js REST API server withExpress Framework andMongoDB database. This tutorial will be covered based on Ubuntu 20 Operating System.
sudo apt updatesudo apt upgradesudo apt install -y curlcurl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
- Check node is installed successfully.
node --version
This command will show you the node version something like thisv16.1.0
- Check npm version.
npm --version
This command will show you the npm version something like thisv8.3.0
- Create an empty folder or directory.
sudo mkdir testcd test
- For creating new node project or app run the command below and complete all the steps.
npm init
- package name :node_express_test_server
- version :keep it blank and press enter
- description :keep it blank and press enter
- entry point :keep it blank and press enter
- test command :keep it blank and press enter
- git repository :keep it blank and press enter
- keywords :keep it blank and press enter
- author :keep it blank and press enter
- license :keep it blank and press enter
At the last step , the command prompt will ask you to confirm, typey oryes
- Now create a file namedapp.js in the main direcotry. You can use GUI to create this file also.
touch app.js
- Now install some packages to create complete REST api server including Express framework.
# Main REST API framework for Nodenpm install express # Allow outside visitors to visit our servernpm install cors # Helps to connect MongoDB with Express frameworknpm install mongoose # Helps to restart server, very handy in development modenpm install nodemon
- Go topackage.json file and add yourapp.js file into start command.
..."scripts": { "start": "nodemon app.js" },...
- Create a directory nameddb and create a file nameddatabase.js in thisdb directory. Then paste the code below intodatabase.js file. This file will help us to connect with our MongoDB database.
var mongoose = require('mongoose')# Try with 127.0.0.1 if localhost do not workmongoose.connect('mongodb://127.0.0.1:27017/node_express_db', {useNewUrlParser: true, useUnifiedTopology: true}) var conn = mongoose.connection conn.on('connected', function() { console.log('database is connected successfully')});conn.on('disconnected',function(){ console.log('database is disconnected successfully')}) conn.on('error', console.error.bind(console, 'connection error:')) module.exports = conn
- Create another directory namedmodels and create a file nameduserModel.js & paste the code below.
var mongoose=require('mongoose')var db = require('../db/database') // create an schemavar userSchema = new mongoose.Schema({ name:String, email: String, address: String, }); userTable=mongoose.model('users',userSchema, 'users') module.exports = userTable
- Openapp.js file and add the code below.
const express = require('express')const cors = require('cors')const mongoose = require('mongoose')const app = express()const port = 3000/*Set the cors option to access this server from outside of the world. Don't forget to limit this access when you are in production mode*/const corsOptions = { origin: '*', optionsSuccessStatus: 200,}app.use(cors(corsOptions));/*It will handle large amount of json body data to receive and transfer over request*/app.use(express.json({ limit: '20mb' }))app.use(express.urlencoded({ extended: false, limit: '20mb' }))//Our database connection helperconst dbConn = require('./db/database');// Our user modelconst userModel = require('./models/userModel');//-- Welcome API, our first APIapp.get('/welcome', (req, res) => { return res.json({ code: 200, message : "Congratulations! Your Node js REST API server with Express framework and MongoDB is ready!" });});//-- Create new user APIapp.post('/createUser', async (req, res) => { if (!Object.keys(req.body).length) { return res.json({ status: 501, message: "No body provided" }) } userModel.findOne({ email: req.body.email }) .then((user) => { //------------ Checking user exists or not if (user) return res.json({ status: 401, data: "User already exists with this phone number" }) //--- If user not created before, create now userModel.create(req.body) .then((result) => { return res.json({status : 200, message : "User created successfully", result : result}) }) .catch((err) => { return res.json({status : 501, message : "Something bad happened, Error : "+ err}) }) }) .catch((err) => { return res.json({status : 501, message : "Something bad happened, Error : "+ err})})})//-- Show all usersapp.get("/getAllUsers", async (req, res) => { userModel.find() .then((result) => { return res.json({status : 200, result : result}) }) .catch((err) => { return res.json({status : 501, message : "Something bad happened, Error : "+ err}) })})//start node server on 3000 portapp.listen(port, () => { console.log(`Server started successfully on port ${port}`) })
- Now start the server.
npm start
If you see something like below then congratulations! You are successfully running Node REST API server with Express framework and MongoDB database!
- localhost:3000/welcome
- localhost:3000/createUser
- localhost:3000/getAllUsers
About
No description, website, or topics provided.
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published
Uh oh!
There was an error while loading.Please reload this page.