0

imagine in a left hand the following server #1 (in our Datacenter) Mongodb nodejs Some Nodejs script that read and write to MongoDB

in the Right hand a nginx/apache server #2 a web app for displaying mongodb and send information to mongo

how can i , with javascript/Jquery on server 2 request the server #1, and get the Json response

the purpose is to build a web app that read & write to mongo using JS/jquery on a "client side" server2

i was using a REst API service since now, but due to lot of bugs/changes, i want to be independant of it.. how can i simply write a nodejs service that allow me to send get/put/delete etc.. to nodejs Script and ge t the json back ?

thanks for any help

Pat Needham
  • 5,698
  • 7
  • 43
  • 63
jeebee
  • 21
  • 5
  • your question is not much clear. I think you need to revers proxy from server2 to server1. You may refer http://stackoverflow.com/questions/5009324/node-js-nginx-what-now – Arif Khan Jul 25 '16 at 14:34

1 Answers1

0

On the server with MongoDB, you can write a basic NodeJS/Express application that reads from Mongo and outputs JSON data. For example, say you have a users collection in your database:

var MongoClient = require('mongodb').MongoClient
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// Connection URL
var url = 'mongodb://localhost:27017/yourDatabaseName';

app.get('/users', function(req, res) {
    var getUsers = function(db, callback) {
        var collection = db.collection('users');
        collection.find({}, {password: 0}).toArray(function(err, docs) {
            callback(docs);
        });
    };
    MongoClient.connect(url, function(err, db) {
        getUsers(db, function(docs) {
            res.json(docs);
        });
    });
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

Then on server #2 you can use jQuery's getJSON() method to access that data from the url server1's IP:3000/users like so:

$.getJSON( "server1IP:3000/users", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  });

  $( "<ul/>", {
    "class": "my-new-list",
    html: items.join( "" )
  }).appendTo( "body" );
});

As for the other CRUD operations like PUT, DELETE, etc. you can use MongoDB's native NodeJS driver as I did in this example or an ORM like Mongoose

Pat Needham
  • 5,698
  • 7
  • 43
  • 63
  • Thanks that's work Terrific, but i need to add the following http://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue to avoid a No 'Access-Control-Allow-Origin' error – jeebee Jul 25 '16 at 11:41