Server.js Code:
//built-in HTTP module, provides HTTP server and client functionality (path module is also built-in module, MIME is add-on module)varHttp=require ("http");//Create a server, create an HTTP server to invoke the Http.createserver () function, which has only one parameter, is a callback function that the server calls once each time it receives an HTTP request. Each HTTP request received by the server will trigger the request function with the new requests and response objects. varServer=http.createserver (function(REQ,RESP) {Console.log ("Request Address is:" +Req.url); //This allows the setting to resolve cross-domain requestsResp.writehead (200,{"Content-type": "Text/plain;charset= ' Utf-8 '", ' access-control-allow-origin ': ' * ', ' Access-control-allow-methods ': ' Put,post,get,delete,options '}); varArr=[]; //Creating Objects varemp=NewObject; Emp.name= "Atila"; Emp.age=39; Emp.id= "007"; Arr.push (EMP); varEmp2={}; Emp2.name= "Lingling Paint"; Emp2.age=29; Emp2.id= "008"; Arr.push (EMP2); //Json.stringify used to convert an object to JSON text, Json.parse to convert the JSON text to an object varRetval=json.stringify (arr); Resp.end (retval);//Response Object End Response});//Server starts operation listening PortServer.listen ("localhost",function() {Console.log ("Server started operation, listening on port 3000 ...");});
Page code:
<!DOCTYPE HTML><HTMLLang= "Utf-8"><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/><Head> <title>Get data from node. js</title> <Scriptsrc= "./js/jquery-1.7.2.min.js"type= "Text/javascript"></Script> </Head> <Body> <DivID= "Mydiv"></Div> </Body></HTML><Scripttype= "Text/javascript"><!--/****************************************************** the startup function called when the window is loaded ****************************************** ***********/$ (document). Ready (function() {loadremotedata ();}); /****************************************************** Remove remote server data ********************************************* ********/functionLoadremotedata () {varURL="http://127.0.0.1:3000"; //$.getjson JSON text used to get the remote return varStr=""; $.getjson (URL,function(data) {
Traversing a JSON array for(varI=0, L=Data.length;i<L;i++){ for(varKeyinchData[i]) { //alert (key+ ': ' +data[i][key]);Str+=Key+':'+Data[i][key]+","; } STR+=";"; } $("#myDiv"). html (str); });}// -</Script>
node. JS uses jquery to get an example of a JSON array returned by NODEJS HTTP server