Nodejs Advanced (5)-Receive parameters

Source: Internet
Author: User

1. Get request parameter Receive

Let's simply give an example of a parameter that needs to be received

If there is a search function, find the keyword to be received from the URL, http://localhost:8000/search?keyword= earth. Using the URL module in the previous Advanced 3 tutorial, "Nodejs Advanced (3)-route processing", we know that the Receive method is written as follows

1 //----------------6_param------------------------------------2 varHTTP = require (' http '); 3 varurl = require (' URL ')); 4 varRouter = require ('./router ')); 5Http.createserver (function(Request, response) {6if(request.url!== "/favicon.ico") {//Clear 2nd this access7varRdata = Url.parse (Request.url,true). Query;//Get Parameters8if(rdata[' keyword ']!=undefined) {  9Console.log (rdata[' keyword ']); Ten         }        OneConsole.log ("Server execution Complete");  A Response.End ();  -     }                           -}). Listen (8000);  theConsole.log (' Server running at Http://127.0.0.1:8000/');

Then in our console will output query this "Earth".

Get requests we can all get the parameters in this way.

2. Post request parameter Receive

In the case of a POST request, these parameters are not passed through the URL and are included in the request body. The flow in the request body needs to be received in the form of an event

Req.on (' Data ', function (chunk) {///through the Data event listener function of req, which is added to the post variable whenever the request body is received

Post + = chunk;

});

We create a new page with a POST request

1 <HTML>2 <Head>3 </Head>4 <Body>5 Login:6 <P>This is a paragraph</P>7 <H1>Style 1</H1>8 <formAction= "/submitlogin"Method= "POST">9User name:<inputvalue=""name= "Name">TenPassword:<inputvalue=""name= "pwd"> One <inputtype= "Submit"value= "Submit"> A </form> - <!--img src= "./showimg" ></img - - </Body> the <HTML>

We request login, there are two entries name and PWD, when we enter values and click Submit, will send a POST request to Http://localhost:8000/submitLogin

We extend the router.js to add submitlogin processing methods.

It was previously necessary to introduce ' querystring ', which was used to convert the URL parameter string to the Parameter object.

You need to learn two common ways to learn

1)require (' querystring '). Parse ("name=eee&pwd=123") Result: Object {name: "eee", pwd: "123"}

2)require (' QueryString '). Stringify ({name: ' eee ', pwd: ' 123 '}) Result: "Name=eee&pwd=123"

1 //-----------------router.js--------------------------------2 varFile = require ('./models/file '));3 varurl = require (' URL ')); 4 varQueryString = Require (' querystring ');//post needs to be imported5module.exports={6Loginfunction(req,res) {7Res.writehead, {' Content-type ': ' text/html '}); 8vardata = File.readfilesync ('./views/login.html ')); 9 res.write (data); Ten Res.end ();  One     }, ARegisterfunction(req,res) { -varData=file.readfilesync ('./views/register.html ');//using synchronous reads - res.write (data); the res.end (); -     }, -SHOWIMG:function(req,res) { -File.readimg ('./imgs/dog.jpg ', res);//using synchronous reads +     }, -Submitlogin:function(req,res) { +         varPost = ';//defines a post variable for staging the request body information AReq.on (' Data ',function(Chunk) {//The data event listener function of req is added to the post variable whenever the request body is received . atPost + =Chunk;  -         });  -//-------Note Asynchronous------------- -Req.on (' End ',function(){//After the end event is triggered, the post is parsed into the true POST request format via Querystring.parse and then returned to the client.  -Post =Querystring.parse (POST);  -Console.log (' Name: ' +post[' name ']+ ' \ n ');  inConsole.log (' pwd: ' +post[' pwd ']+ ' \ n '); -             if(post[' name ']== "fff" &&post[' pwd ']== "123") {//Simple write login successful match toRes.write ("Login Successful! ") +}Else{ -Res.write ("User name password is incorrect") the             } * Res.end ();  $         }); Panax Notoginseng     } -}

When we want to enter the login page username and password parameters, if input FFF and 123 this time jump to Loginsubmit output login success!

If you enter a different value jump, you will be prompted: The username password is incorrect

Nodejs Advanced (5)-Receive parameters

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.