Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
NotificationsYou must be signed in to change notification settings

Turzoxpress/Node_REST_API_Server_Express_MongoDB

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Alt Node.js Express MongoDB

How to create REST API server with Node.js, Express Framwork & MongoDB database?

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.

Alt Node.js Express MongoDB

InstallingNode.js version 16 on Ubuntu machine

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
  1. package name :node_express_test_server
  2. version :keep it blank and press enter
  3. description :keep it blank and press enter
  4. entry point :keep it blank and press enter
  5. test command :keep it blank and press enter
  6. git repository :keep it blank and press enter
  7. keywords :keep it blank and press enter
  8. author :keep it blank and press enter
  9. license :keep it blank and press enter

At the last step , the command prompt will ask you to confirm, typey oryes

And, that's all! Your first node app created successfully!

Alt Node.js Express MongoDB

  • 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"  },...

Alt Node.js Express MongoDB

  • 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

As we have created our model, we can now proceed to create some test APIs.

  • 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!


Alt Node.js Express MongoDB

Now it's time to test our newly created APIs with Postman.

  • localhost:3000/welcome

Alt Node.js Express MongoDB

  • localhost:3000/createUser

Alt Node.js Express MongoDB

  • localhost:3000/getAllUsers

Alt Node.js Express MongoDB

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp