Tag: Main text response post params func property lis No
node. JS Get/post Request
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/pos t 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.
Instance
var http = require (' http '), var url = require (' URL '), var util = require (' util '); Http.createserver (function (req, res) { Res.writehead ($, {' Content-type ': ' Text/plain; Charset=utf-8 '}); Res.end (Util.inspect (Url.parse (Req.url, True))). Listen (3000);
Visit the http://localhost:3000/user?name= Novice Tutorial in the browser &url=www.runoob.com then view the results returned:
Gets the parameters of the URL
We can use the Url.parse method to parse the parameters in the URL, the code is as follows:
Instance
var http = require (' http '), var url = require (' URL '), var util = require (' util '); Http.createserver (function (req, res) { Res.writehead ($, {' Content-type ': ' Text/plain '}); Parse URL parameter var params = Url.parse (Req.url, true). query; Res.write ("website name:" + params.name); Res.write ("\ n"); Res.write ("website URL:" + params.url); Res.end (); }). Listen (3000);
Visit the http://localhost:3000/user?name= Novice Tutorial in the browser &url=www.runoob.com then view the results returned:
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.
Basic syntax Structure description
var http = require (' http '), var url = require (' URL '), var util = require (' util '); Http.createserver (function (req, res) {Res.writehead ($, {' Content-type ': ' Text/plain;charset=utf-8 '}); Parse URL parameter var params = Url.parse (Req.url, true). Query; Res.write ("website name:" + params.name); Res.write ("\ n"); Res.write ("website URL:" + params.url); Res.end (); }). Listen (3000);
The following instance form submits and outputs data via POST:
Instance
var http = require (' http '); var querystring = require (' querystring '); var posthtml = '
To perform the result Gif demo:
node. JS Get/post Request