In many scenarios, our servers need to interact with the user's browser, such as form submissions.
The get/post request is typically used by the form submission to the server.
In this section we will introduce you to the node. JS get/post request.
Get the GET Request content
Because the GET request is embedded directly in the path, the URL is the complete request path, including the following section, so you can manually parse the following contents as parameters of the GET request.
This function is provided by the parse function in the URL module in node. js.
Varhttp= Require(' HTTP ');VarUrl= Require(' URL ');VarUtil= Require(' Util ');http.Createserver(function(Req,Res){Res.Writehead (200, { ' Content-type ' : ' text/plain ' }); . (util. Inspect (url. Parse (req. Url, truelisten3000
Access in the browser http://localhost:3000/user?name=w3c&[email protected]
and then view the returned results:
Get POST Request Content
The contents of the POST request are all in the request body, HTTP. Serverrequest does not have a property content of the request body, because waiting for a request body transfer can be a time-consuming task.
such as uploading files, and many times we may not need to ignore the content of the request body, malicious post requests will greatly consume the resources of the server, all node. js By default will not parse the request body, when you need to do it manually.
Varhttp= Require(' HTTP ');VarQueryString= Require(' QueryString ');VarUtil= Require(' Util ');http.Createserver(function(Req,Res){ VarPost= ‘‘; Defines a post variable for staging the request body informationReq.On(' Data ', function(Chunk){ The Data event listener function of req is added to the post variable whenever the request body is received.Post+=Chunk; });Req.On( ' end ' , function () { Span class= "PLN" > //after the end event is triggered, the post is parsed into a true POST request format by Querystring.parse and then returned to the client. post = Querystring.post Res.< Span class= "KWD" >end (util. Inspectpost). listen3000
node. JS Get/post Request