node. JS HTTP Server object and get, POST request

Source: Internet
Author: User

The previous blog learned the request and response, 2 reads 2 times write, but one question is how the client writes to know when the request arrives. So the HTTP server object appears. It provides the basic framework for implementing an HTTP server. It listens to the underlying socket of the port and receives the request, and then sends a handler that responds to the client connection.

It provides a few events:

Request: Triggered when the server receives a client request. For example: function callback (Request,response) {}.

Connection: Triggered when a new TCP stream is established. Example: function callback (SOCKET)

Close: Triggered when the server shuts down, the callback does not receive parameters.

Checkcontinue: Triggered when a request is received that includes the expected 100-continue header. Even if this event is not handled, the default event handler responds. For example: function callback (request,response) {}

Connect: Issued when an HTTP connect request is received. Callback receive request, response, head. Example: Function callback (Request,response,head)

Upgrade: Emitted when the client requests an HTTP upgrade. function Callback (Request,response,head)

Clienterror: Emitted when a client connection socket issues an error. function callback (error,socket) {}

To start the HTTP server, first create the object using the Createserver ([Requestlistener]) method and then pass through Listen (Port,[hostname],[backlog],[callback]).

Port: Ports

Hostname: Host Name

Backlog (Backlog): Specifies the maximum number of pending connections that are allowed to be queued. Default 511.

Callback (CALLBACK): Specifies the callback handler to execute when the server has started listening on the specified port.

A connection to a file system can be made in two ways:

Listen (Path,[callback]): File path

Listen (Handle,[callback]): Receives a file descriptor handle that has already been opened.

You can use the close ([callback]) method if you want to stop listening.

The above understanding the next HTTP Server object, the following with GET, post experiment.

GET:

varHTTP = require (' http ');varMessages = [  ' Hello World ',  ' From a basic node. JS Server ',  ' Take Luck '];http.createserver (function(req, res) {Res.setheader ("Content-type", "text/html"); Res.writehead (200); Res.write (' ); Res.write (' <body> ');  for(varIdxinchmessages) {Res.write (' \n); } res.end (' \n</body>);}). Listen (8080);varOptions ={hostname:' localhost ', Port:' 8080 ',  };functionHandleresponse (response) {varServerdata = ' '; Response.on (' Data ',function(chunk) {Serverdata+=Chunk;  }); Response.on (' End ',function() {Console.log ("Response Status:", Response.statuscode); Console.log ("Response Headers:", response.headers);  Console.log (Serverdata); });} Http.request (Options,function(response) {handleresponse (response);}). End ();
Response status:200' content-type ': ' text/html ',  ' Mon, Mar 12:51:06 GMT ',  ' Close ',  ' transfer-encoding ': ' chunked ' }

POST:

varHTTP = require (' http '); Http.createserver (function(req, res) {varJsondata = ""; Req.on (' Data ',function(chunk) {Jsondata+=Chunk;  }); Req.on (' End ',function () {    varReqobj =Json.parse (Jsondata); varResobj ={message:"Hello" +Reqobj.name, question:"Is you a good" + Reqobj.occupation + "?"    }; Res.writehead (200);  Res.end (Json.stringify (resobj)); });}). Listen (8088);varHTTP = require (' http ');varOptions ={host:' 127.0.0.1 ', Path:‘/‘, Port:' 8088 ', Method:' POST '};functionReadjsonresponse (response) {varResponseData = ' '; Response.on (' Data ',function(chunk) {ResponseData+=Chunk;  }); Response.on (' End ',function () {    varDataobj =Json.parse (ResponseData); Console.log ("Raw Response:" +responsedata); Console.log ("Message:" +dataobj.message); Console.log ("Question:" +dataobj.question); });}varreq =http.request (options, Readjsonresponse); Req.write (' {' name ': ' Bilbo ', ' occupation ': ' Burglar '} '); Req.end ();
Raw Response: {"message": "Hello Bilbo", "question": "Is you a good burglar?" }message:hello Bilboquestion:are you a good burglar?

The port number used for the first time is 8080, then the following error is reported. Change the port number to be OK.

events.js:141ThrowEr//unhandled ' ERROR ' event^error:listen eaddrinuse: ::8080At object.exports._errnoexception (util.js:870:11) at Exports._exceptionwithhostport (util.js:893:20) at Server._listen2 (net.js:1236:14) at Listen (Net.js:1272:10) at Server.listen (net.js:1368:5) at Object.<anonymous> (c:\Users\Administrator\Desktop\nodejs-mongodb-angularjs-web-development-master\ch07\http_ Server_post.js:16:4) at Module._compile (module.js:409:26) at Object.module._extensions. JS (module.js:416:10) at Module.load (module.js:343:32) at Function.module._load (module.js:300:12)

Above the basic HTTP this piece of basic learning, for HTTPS can be used HTTPS client and server, and HTTP is not very different, is a few more options.

For the lower socket, TCP, UDP these are skipped first, these do not use the web may not be used, the general study once again back to review the study.

node. JS HTTP Server object and get, POST request

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.