1. How to use Nodejs to access our MongoDB database.
1. New start a WebService server var http = require (' http ');
3. Introduce the URL module to the front-end request identification var URL = require (' URL ');
You can convert the specified string to a JSON object var qs = require (' querystring ');
Qs.parse () var getuser = require ('./db.js ') [0]; 2. Create service Http.createserver (function (request,response) {response.writehead (') ', {' Content-type ': ' A
Pplication/json;charset=utf-8 ', ' access-control-allow-origin ': ' * '});
Gets the Access object var _url = Request.url;
Console.log (_url);
var _path = Url.parse (_url). pathname;//GET request Address Console.log (_path); 4. Define a standard/users access MongoDB switch (_path) {case "/user"://When the browser enters the user page, call the Get in Db.js User method, get the data in//query ID 009 of the Users information 1. Design a new interface request path/userbyid//2. In the switch to Judge Intercept//3.
Db.js inside implement a new query method to get the data var _search = Url.parse (_url). Search; VaR options = {}; Dynamically assigned to JSON//options[array [0]] = array [1] value//?/USER?AGE=30&USERNAME=B// Find ({age=30&username=b}) to get if (_search==null) {CONSOLE.L
OG ("Query All");
options={}; }else{console.log ("Query single");///userid=1008//options-->{"userId": "1008
"} var _ns = _search.substring (1,_search.length);
_ns = Qs.parse (_ns);
Console.log (_ns);
options = _ns;
} console.log ("Access to MongoDB database");
GetUser (Options,function (callback) {Response.Write (Json.stringify (callback));
Response.End ();
});
Break Case "/userbyid": var jsons = ' {userid ': '009 "," username ":" admins "};
Response.Write (jsons);
Response.End ();
Question://1. Different naming is not a problem. 2. Designed so that each interface features a single, interface reusability is very low//design will query all data and query a single data interface are placed in the/USER interface//CORE issues:/user recognition Do I want to query a single or query all data//query all the interface/user//Query Single interface/user?userid=1009//1. Is whether the user hair/user| |
/user?userid=1009 requests can be intercepted by the switch inside the selection branch to//2. To determine whether the search exists inside a GET request, if there is a single query, if there is no query all break;
Case "/login"://1. Get the data in post var _data = ';
2.request.addlistener (); To obtain the data submitted by post//is to listen for the data event, and the value will appear in the callback function as long as there is.
Request.addlistener (' Data ', function (data) {_data+=data;//) each time the data obtained is a single character
Get the full string}); Data received Request.addlistenER (' End ', function (data) {Console.log (_data);
var ops = Qs.parse (_data);
Console.log (OPS);
var message = {}; GetUser (Ops,function (res) {if (res.length==0) {Message.statu
s = "false";
Message.desc = "Username password error";
Message.time = "2016/09/09";
}else{Message.auth = "lawful user";
Message.status = "true";
Message.desc = "landing success";
Message.role = "admin";
} Response.Write (Message) (json.stringify);
Response.End ();
})//Find ({username: "", Password: ""}); });
Console.log ("This is login API");
Break
Case "/goods": Console.log ("only given false json");
Break
Case "/favicon.ico": break; Firefox browser plugins rest poster,rest API Tool}//5. You need to download a nodejs access MongoDB plugin via npm//npm install MongoDB--save-
Dev Local//6. New Db.js in Db.js to visit our mongdb//response.end ();
}). Listen (3080);
Db.js inside to visit our mongdb GetUser is case "/user": when the output of the data.
Getgoods is the case "/goods": When the output of the data.
Just write different interfaces or data to return to them. 1. The meaning of the callback is that when accessing the database successfully, the data is sent back to/**db layer implementation **/var getuser = function (options,callback) {//implementation specific steps//1. Introducing Support node Access mo
Ngodb plug-in var MongoDB = require (' MongoDB '); 2. Get the connection to the database server new MongoDB. Server (ip,port,options) var server = new MongoDB.
Server (' 127.0.0.1 ', 27017,{auto_connection:true}); 3. Get the database instance new MongoDB through the connection. Db (' database name ', get Connection object with database, security policy) var appdb = new MongoDB. Db (' App_dB ', server,{safe:true});
4. Open the MongoDB database//Open (function (err, instance) {////}); Appdb.open (function (err,appdb) {if (!err) {//5. To do the next step, open the collection of stored data//appdb.collection ( ' The name of the database | |
Name of the collection ', Security Policy, function () {}) appdb.collection (' app_db ', {safe:true},function (err,collection) { if (!err) {//6. In collection to get Data collection.find (options). ToArray (Functi
On (err,doc) {//find can query//7 based on criteria. The data will be put into the callback if (!err) {
Callback (DOC);
}
});
}
});
}
});
var getgoods = function (callback) {} module.exports = [getuser,getgoods]; HTML input Box <div> username: <input id= "username" ><br/> Password: <input id= "Password" > <br/> <button id= "BTN" ≫ login </button> </div> <script type= "Text/javascript" >//1. When to start accessing the login interface.
var _service = "Http://127.0.0.1:3080/login";
$ ("#btn"). Click (function () {var _u = $ ("#username"). Val ();
var _p = $ ("#password"). Val ();
var _json = {username:_u,password:_p};
2. Trigger the login with what changes.
$.post (_service,_json,function (data) {Console.log ("service-side status value");
Console.log (data);
});
});