NodeJS HTTP Module

Source: Internet
Author: User

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 ');
    • 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
    • Client.js
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.