node. JS provides an HTTP module for building HTTP server and client.
Create a Web server
1 /**2 * Node-http Service side3 */4Let HTTP = require (' http ');5Let URL = require (' URL ');6Let FS = require (' FS ');7 8 //Creating a server9Let Server = Http.createserver ((req, res) = = {Ten //parsing Requests OneLet pathname = Url.parse (req.url). Pathname;//shaped like '/index.html ' AConsole.log (' Receive a request for file ' + pathname + ')); - - //Read File contents theFs.readfile (PATHNAME.SUBSTR (1), (err, data) = { - if(err) { -Console.log (' File read failed: ' +err); - + //Setting 404 Responses -Res.writehead (404, { +' Content-type ': ' text/html ' A }); at } - Else { - //Status Code: -Res.writehead (200, { -' Content-type ': ' text/html ' - }); in - //Response File Contents to Res.write (data.tostring ()); + } - the //Send Response * res.end (); $ });Panax Notoginseng }); - theServer.listen (8081); + AConsole.log (' service running at: http://localhost:8081, please visit: http://localhost:8081/index.html ');
1 <! DOCTYPE html> 2 3 4 <meta charset= "UTF-8" > 5 <title>node http</title> 6 7 <body> 8 9 </body>
Run server.js , open browser access.
Create Client
1 /**2 * Node HTTP Create client3 */4Let HTTP = require (' http ');5 6 //Request Options7Let options = {8Host: ' localhost ',9Port: ' 8081 ',TenPath: '/index.html ' One }; A - //callback function for handling responses -Let callback = (res) = = { the //keep updating your data -Let BODY = "; - -Res.on (' Data ', (data) = { +Body + =data; - }); + ARes.on (' End ', () = { atConsole.log (' Data reception complete '); - Console.log (body); - }); - } - - //sending requests to the server inLet req =http.request (options, callback); -Req.end ();
Run server.js , and then run client.js .
NodeJS HTTP Module