In the tutorial, we show you how to POST/GET form data to/from MongoDB in NodeJS/Express application using Mongoose with Ajax JQuery & Bootstrap view.
Related posts:
– Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose
– Integrate NodeJS/Express – JQuery Ajax POST/GET – Bootstrap view
Contents
Goal
Technologies
– NodeJS/Express
– Mongoose
– MongoDB
– JQuery Ajax
– Bootstrap
We create a NodeJS/Express project as below structure:
/NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB /app /config mongodb.config.js /controllers user.controller.js /models user.model.js /routes user.route.js /node_modules /resources /static /js getrequest.js postrequest.js /views 404.html index.html app.js package.json |
Run above project then makes POST/GET requests, results:
-> Bootstrap view:
-> MongoDB’s collections:
Practice
Setting up NodeJS/Express project
Create a folder: ‘NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB’:
mkdir NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB cd NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB |
Then init NodeJS project, see prompts:
NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB>npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (nodejs-express-ajax-jquery-bootstrap-mongodb) version: (1.0.0) description: building a NodeJS/Express web-app to POST/GET data from MongDB via Mongoose - Ajax JQuery + Bootstrap view entry point: (index.js) server.js test command: git repository: keywords: NodeJS, Express, MongoDB, Mongoose, JQuery, Bootstrap author: grokonez.com license: (ISC) About to write to C:\Users\pc\Desktop\nodejs\NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB\package.json: { "name": "nodejs-express-ajax-jquery-bootstrap-mongodb", "version": "1.0.0", "description": "building a NodeJS/Express web-app to POST/GET data from MongDB via Mongoose - Ajax JQuery + Bootstrap view", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "NodeJS", "Express", "MongoDB", "Mongoose", "JQuery", "Bootstrap" ], "author": "grokonez.com", "license": "ISC" } Is this ok? (yes) yes |
-> Install Express, Body-Parser, Mongoose:
npm install express body-parser mongoose --save |
-> see package.json file:
{ "name": "nodejs-express-ajax-jquery-bootstrap-mongodb", "version": "1.0.0", "description": "building a NodeJS/Express web-app to POST/GET data from MongDB via Mongoose - Ajax JQuery + Bootstrap view", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "NodeJS", "Express", "MongoDB", "Mongoose", "JQuery", "Bootstrap" ], "author": "grokonez.com", "license": "ISC", "dependencies": { "body-parser": "^1.18.2", "express": "^4.16.3", "mongoose": "^5.0.17" } } |
Frontend
Create Bootstrap views
– ./view/index.html file:
<!DOCTYPE html> <html lang="en"> <head> <title>JQuery Ajax - Bootstrap - NodeJS/Express - MySQL</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="/static/js/getrequest.js"></script> <script src="/static/js/postrequest.js"></script> </head> <body> <div class="container"> <div class="col-sm-4"> <h3>NodeJS/Express Post/Get Ajax</h3> <div> <form id="userForm"> <div class="form-group"> <label for="firstname">FirstName:</label> <input type="text" class="form-control" id="firstname" placeholder="Enter FirstName"/> </div> <div class="form-group"> <label for="lastname">LastName:</label> <input type="text" class="form-control" id="lastname" placeholder="Enter LastName"/> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> <div id="postResultDiv"> </div> <br> <div> <button id="allUsers" type="button" class="btn btn-default">Users</button> <div id="getResultDiv"> <ul class="list-group"> </ul> </div> </div> </div> </div> </body> </html> |
– ./views/404.html file:
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="jumbotron text-center"> <h1>404 Error!</h1> <p>PAGE NOT FOUND</p> </div> </body> </html> |
Implement Ajax JQuery to Post/Get data
– For JQuery Ajax POST request, we implement a ./resources/static/js/postrequest.js file:
$( document ).ready(function() { // SUBMIT FORM $("#userForm").submit(function(event) { // Prevent the form from submitting via the browser. event.preventDefault(); ajaxPost(); }); function ajaxPost(){ // PREPARE FORM DATA var formData = { firstname : $("#firstname").val(), lastname : $("#lastname").val() } // DO POST $.ajax({ type : "POST", contentType : "application/json", url : window.location + "api/users/save", data : JSON.stringify(formData), dataType : 'json', success : function(user) { $("#postResultDiv").html("<p>" + "Post Successfully! <br>" + "--> " + user.firstname + " " + user.lastname + "</p>"); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); // Reset FormData after Posting resetData(); } function resetData(){ $("#firstname").val(""); $("#lastname").val(""); } }) |
– For JQuery Ajax Get request, we implement a ./resources/static/js/getrequest.js file:
$( document ).ready(function() { // GET REQUEST $("#allUsers").click(function(event){ event.preventDefault(); ajaxGet(); }); // DO GET function ajaxGet(){ $.ajax({ type : "GET", url : "/api/users/all", success: function(result){ $('#getResultDiv ul').empty(); $.each(result, function(i, user){ $('#getResultDiv .list-group').append(user.firstname + " " + user.lastname + "<br>") }); console.log("Success: ", result); }, error : function(e) { $("#getResultDiv").html("<strong>Error</strong>"); console.log("ERROR: ", e); } }); } }) |
Backend
Create Mongoose model
– ./app/models/user.model.js file:
const mongoose = require('mongoose'); const UserSchema = mongoose.Schema({ firstname: String, lastname: String }); module.exports = mongoose.model('User', UserSchema); |
Configure MongoDB connection
– ./app/config/mongodb.config.js file:
module.exports = { url: 'mongodb://localhost:27017/nodejs-demo' } |
Create Express Routes
– ./app/routes/user.route.js file:
module.exports = function(app) { var express = require("express"); var router = express.Router(); const users = require('../controllers/user.controller.js'); var path = __basedir + '/views/'; router.use(function (req,res,next) { console.log("/" + req.method); next(); }); app.get('/', (req,res) => { res.sendFile(path + "index.html"); }); // Save a User to MongoDB app.post('/api/users/save', users.save); // Retrieve all Users app.get('/api/users/all', users.findAll); app.use("/",router); app.use("*", (req,res) => { res.sendFile(path + "404.html"); }); } |
Implement Controllers
– ./app/controllers/user.controller.js file:
const User = require('../models/user.model.js'); // Save FormData - User to MongoDB exports.save = (req, res) => { console.log('Post a User: ' + JSON.stringify(req.body)); // Create a Customer const user = new User({ firstname: req.body.firstname, lastname: req.body.lastname }); // Save a Customer in the MongoDB user.save() .then(data => { res.send(data); }).catch(err => { res.status(500).send({ message: err.message }); }); }; // Fetch all Users exports.findAll = (req, res) => { console.log("Fetch all Users"); User.find() .then(users => { res.send(users); }).catch(err => { res.status(500).send({ message: err.message }); }); }; |
Implement App.js
– ./app.js file:
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(express.static('resources')); global.__basedir = __dirname; // Configuring the database const dbConfig = require('./app/config/mongodb.config.js'); const mongoose = require('mongoose'); mongoose.Promise = global.Promise; // Connecting to the database mongoose.connect(dbConfig.url) .then(() => { console.log("Successfully connected to MongoDB."); }).catch(err => { console.log('Could not connect to MongoDB.'); process.exit(); }); require('./app/routes/user.route.js')(app); // Create a Server var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("App listening at http://%s:%s", host, port) }) |
Run & Check results
Start NodeJS server:
-> Logs:
NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB>node app.js App listening at http://:::8081 Successfully connected to MongoDB. /GET Post a User: {"firstname":"Jack","lastname":"Davis"} Post a User: {"firstname":"Mary","lastname":"Taylor"} Post a User: {"firstname":"Peter","lastname":"Thomas"} Post a User: {"firstname":"Amos","lastname":"Nelson"} Post a User: {"firstname":"Craig","lastname":"White"} Post a User: {"firstname":"Laura","lastname":"Lewis"} Post a User: {"firstname":"Steven","lastname":"Harris"} Post a User: {"firstname":"Paul","lastname":"Moore"} Post a User: {"firstname":"Mary","lastname":"Cook"} Fetch all Users |
-> POST/GET requests:
Sourcecode
To run below sourcecode, follow below guides:
step 0: download & extract zip file -> we have a folder 'NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB' step 1: cd NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB step 2: npm install express body-parser mongoose --save step 3: node app.js |
Sourcecode:
NodeJS-Express-Ajax-JQuery-Bootstrap-MongoDB
Last updated on February 6, 2020.
what is window_location in URL?
hi 🙂 bross 🙂
i am from Italy hello. Can you help me translate? /rardor
Thank you very much for the invitation :). Best wishes.
PS: How are you? I am from France 🙂