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 ANGULARJS Code:
<!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTMLNg-app= "Notesapp"> <Head> <MetaCharSet= "Utf-8"> <title>Angularjs Get Nodejs data</title> <Scriptsrc= "Angular1.4.6.min.js"></Script> </Head> <Body> <TableNg-controller= "Mainctrl as CTRL"Border= "1px"> <TRng-repeat= "Member in Ctrl.items"> <TD><spanNg-bind= ' member.id '/></TD> <TD><spanNg-bind= ' Member.name '/></TD> <TD><spanNg-bind= ' Member.age '/></TD> </TR> </Table> </Body></HTML><Scripttype= "Text/javascript"><!--Angular.module ('Notesapp', []). Controller ('Mainctrl',['$http',function($http) {var Self= This; Self.items=[]; varURL="http://localhost:3000"; $http. Get (URL). Then (function(response) {Self.items=Response.data; },function(errresponse) {alert ('Error'+errresponse); }); }]);// -</Script>
Node. JS uses Angularjs to obtain an example of a JSON array returned by Nodejs HTTP service side