Nodejs receive POST request parameters __js

Source: Internet
Author: User
Tags button type readfile
Nodejs receive POST request parametersHow the 1.1-browser sends POST request parameters

1.2-How the service side receives the POST request parameters

POST request parameters are not spliced directly in the URL path, but are sent to the server request in the body of the request three elements: the request line, the request header, the request body 1.1-The way the browser sends the POST request parameters Post request parameters cannot be spliced directly in the URL path, so you typically use AJAX requests to send POST request parameters
Usually submit form form data using POST request

<script>

  //browsers typically use AJAX to send post requests
  $ (' #form '). On (' Sunmit ', function (e) {
    //disable form default commit event
    E.preventdefault ();
    $.ajax ({
      URL: ' heroadd ',
      type: ' Post ',
      dataType: ' JSON ',
      data: $ (this). Serialize (),
      Success:function (data) {
      }
    }
); </script>
Complete Code
<! DOCTYPE html>  
 
1.2-How the service side receives the POST request parameters 

Unlike get requests, the server side receives a POST request parameter that is not available at once, and typically requires multiple parameter data sent by a general post request that is much larger than the fetch request.

1. Service-side Receive form data flow (1) If the amount of data in the form is more, the more times it is sent, if it is less, it may come out at once (2) when receiving form data, you need to listen for data events from the Req object (3) whenever you receive data from a form submission, req The data event is triggered once, and can be obtained by the callback function.
Server side needs to add data stream itself (4) When the data submitted by the receiving form is completed, the Req on event is executed

2. The logical process of processing the form data by the server (1) decoding the data (URL encoding when submitting the Chinese data)
decodeURI (data) (2) Deserializes the URL using QueryString (resolves the URL to split the & and = into key-value pairs) to get an object
QueryString is a Nodejs built-in module dedicated to handling URLs, with only four APIs, see Nodejs official documentation for details The POST request parameter cannot be parsed with a URL module because he is not a URL, but rather a request body object (3) Inserts data into the database

Import QueryString Module (parse POST request data) var querystring = require (' querystring ');

Console.log (Req.method);
        1. Determine whether the form is submitted if (Req.url = = '/heroadd ' && req.method = = ' POST ') by judging the URL path and the request method {/** The process of receiving the POST request parameters from the service side * (1) Register for REQ request to receive data event (this method executes multiple times, requires us to manually accumulate binary data) * * If the amount of data in the form is more, the more times it is sent, if less, it may come out at once * * so then
        When receiving form data, you need to listen to the data event of the Req object to fetch it * * that is, each time a form is received, the data event of the Req is triggered once, and the data of the segment can be obtained by the callback function.

    * (2) to the REQ request registration completes receives the data end event (all data receive completes will execute once this method) * *///Create the blank character superposition data fragment var the ";" 2. Register the data event to receive (every time you receive the data submitted by the form, the method executes once) Req.on (' Data ', function (chunk) {//chunk default is a binary data, and data stitching will automatically to
    String data + + chunk;

    }); 3. When the data submitted by the receiving form is completed, it is possible to further process/register the end event, and all data receive completion is performed once by the method Req.on (' Ends ', function () {//(1). Decodes URLs (URLs
        Encoding in chinese) data = decodeURI (data);

        Console.log (data); The/**post request parameter cannot be resolved using the URL module because he is not a URL, but rather a request body object///(2). Use Querystring deserializes the URL (resolves the URL to split the & and = into a key-value pair) to get an object//querystring is a Nodejs built-in module for handling URLs with only four APIs, see Nodejs Official document var da
        Taobject = querystring.parse (data);
    Console.log (DataObject);
});
 }
Full Code
1. Import HTTP module var http = require (' http ');
Import file module var fs = require (' FS ');
Import path module var path = require (' path ');

Import QueryString Module (parse POST request data) var querystring = require (' querystring ');

2. Create server var app = Http.createserver ();

    3. Add response event App.on (' Request ', function (req, res) {Console.log (Req.method); 1. Determine whether the form is submitted if (Req.url = = '/heroadd ' && req.method = = ' POST ') by judging the URL path and the request mode {/** server receives the stream of POST request parameters       Process * (1) Register for REQ request to receive data event (this method executes multiple times, requires us to manually accumulate binary data) * * If the amount of data in the form is more, the more times it is sent, if less, it may come up once.  * So when receiving form data, you need to listen to the data event of the Req object to fetch it * * that is, whenever you receive a form submission, the Req data event is triggered once, and the callback function allows you to get the segment

        The data * (2) to the REQ request registration completes receives the data end event (all data receive completes will execute once this method)////create the blank character superposition data fragment var the ";" 2. Register the data event to receive (each time the data submitted by the form is received, the method executes once) Req.on (' Data ', function (chunk) {//chunk default is a binary data, and DAT
        A stitching will automatically toString data + + chunk;

        }); 3. When receiving the form submissionAfter the data has been completed, you can further process the//Registration end event, and all data receive completion is performed once by the method Req.on ("End", function () {//(1). Decodes URLs (URLs to
            The text is encoded) data = decodeURI (data);

            Console.log (data);
            The/**post request parameter cannot be resolved using the URL module because he is not a URL, but rather a request body object///(2). Deserialize the URL using QueryString (parse the URL to split the & and = into key-value pairs) to get an object
            QueryString is a Nodejs built-in module for handling URLs with only four APIs, see Nodejs Official document var dataObject = querystring.parse (data);
        Console.log (DataObject);
    });  } if (Req.url = = '/heroadd ' && req.method = = ' POST ') {fs.readfile ('./heroadd.html '), function (Err,
            Data) {if (err) {throw err;
        } res.end (data);
    });
            else if (req.url.indexOf ('/node_modules ') = = 0) {fs.readfile (__dirname + req.url, function (err, data) {
            if (err) {throw err;
            else {res.end (data);
    }
        }); } else {
        Res.end (' request path: ' + Req.url ');

}
});
 4. Listener Port number App.listen (3000, function () {Console.log (' Welcome to King Glory Hero Manager ');

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.