Easily create nodejs servers (10): Process POST requests, nodejspost

Source: Internet
Author: User

Easily create nodejs servers (10): Process POST requests, nodejspost

So far, our servers have no practical use. Next we will start to implement some practical and useful functions.

What we need to do is: select a file, upload the file, and view the uploaded file in the browser.

First, we need a processing area (textarea) for the user to input the content, and then submit it to the server through the POST request.

We add code in the start event processor. The modification of requestHandlers. js is as follows:

Copy codeThe Code is as follows:
Function start (response ){
Console. log ("Request handler 'start' was called .");
Var body = ''<Meta http-equiv = "Content-Type" content = "text/html;' +
'Charset = UTF-8 "/> '+
'</Head>' +
'<Body>' +
'<Form action = "/upload" method = "post">' +
'<Textarea name = "text" rows = "20" cols = "60"> </textarea>' +
'<Input type = "submit" value = "Submit text"/>' +
'</Form>' +
'</Body>' +
'</Html> ';
Response. writeHead (200, {"Content-Type": "text/html "});
Response. write (body );
Response. end ();
}
Function upload (response ){
Console. log ("Request handler 'upload' was called .");
Response. writeHead (200, {"Content-Type": "text/plain "});
Response. write ("Hello Upload ");
Response. end ();
}
Exports. start = start;
Exports. upload = upload;

You can see the effect by accessing http: // localhost: 8888/start in the browser.

Next, we need to trigger the/upload request handler to process the POST request when the user submits the form.

To make the entire process non-blocking, Node. js splits the POST data into many small data blocks, and then passes these small data blocks to the callback function by triggering specific events. Specific events here include data events (indicating that new small data blocks have arrived) and end events (indicating that all data has been received ).

We can achieve this by registering the listener (listener) on the request object. The request object here is the onRequest callback function that will pass the object each time an HTTP request is received.

We put the code on the server, and modify server. js as follows:

Copy codeThe Code is as follows:
Var http = require ("http ");
Var url = require ("url ");
Function start (route, handle ){
Function onRequest (request, response ){
Var postData = "";
Var pathname = url. parse (request. url). pathname;
Console. log ("Request for" + pathname + "received .");
Request. setEncoding ("utf8 ");
Request. addListener ("data", function (postDataChunk ){
PostData + = postDataChunk;
Console. log ("Received POST data chunk '" + postDataChunk + "'.");
});
Request. addListener ("end", function (){
Route (handle, pathname, response, postData );
});
}
Http. createServer (onRequest). listen (8888 );
Console. log ("Server has started .");
}
Exports. start = start;

The above Code does three things: first, we set the encoding format of the received data to UTF-8, and then register the listener of the "data" event to collect the new data blocks received each time, assign the value to the postData variable. Finally, we move the request route call to the end event handler to ensure that it is triggered only after all data is received, trigger only once. At the same time, we also pass the POST data to the request route because the data is used by the request processing program.

Next, on the/upload page,

Let's modify router. js:

Copy codeThe Code is as follows:
Function route (handle, pathname, response, postData ){
Console. log ("About to route a request for" + pathname );
If (typeof handle [pathname] === 'function '){
Handle [pathname] (response, postData );
} Else {
Console. log ("No request handler found for" + pathname );
Response. writeHead (404, {"Content-Type": "text/plain "});
Response. write ("404 Not found ");
Response. end ();
}
}
Exports. route = route;

Then, in requestHandlers. js, we include the data in the response to the upload request:

Copy codeThe Code is as follows:
Function start (response, postData ){
Console. log ("Request handler 'start' was called .");
Var body = ''<Head>' +
'<Meta http-equiv = "Content-Type" content = "text/html;' +
'Charset = UTF-8 "/> '+
'</Head>' +
'<Body>' +
'<Form action = "/upload" method = "post">' +
'<Textarea name = "text" rows = "20" cols = "60"> </textarea>' +
'<Input type = "submit" value = "Submit text"/>' +
'</Form>' +
'</Body>' +
'</Html> ';
Response. writeHead (200, {"Content-Type": "text/html "});
Response. write (body );
Response. end ();
}
Function upload (response, postData ){
Console. log ("Request handler 'upload' was called .");
Response. writeHead (200, {"Content-Type": "text/plain "});
Response. write ("You 've sent:" + postData );
Response. end ();
}
Exports. start = start;
Exports. upload = upload;

The last thing we need to do is to pass the entire message body of the request to the Request Routing and request processing program. We should pass only the parts of POST data that we are interested in to the Request Routing and request processing programs. In our example, we are only interested in the text field.

We can use the previously introduced querystring module for implementation:

Copy codeThe Code is as follows:
Var querystring = require ("querystring ");
Function start (response, postData ){
Console. log ("Request handler 'start' was called .");
Var body = ''<Head>' +
'<Meta http-equiv = "Content-Type" content = "text/html;' +
'Charset = UTF-8 "/> '+
'</Head>' +
'<Body>' +
'<Form action = "/upload" method = "post">' +
'<Textarea name = "text" rows = "20" cols = "60"> </textarea>' +
'<Input type = "submit" value = "Submit text"/>' +
'</Form>' +
'</Body>' +
'</Html> ';
Response. writeHead (200, {"Content-Type": "text/html "});
Response. write (body );
Response. end ();
}
Function upload (response, postData ){
Console. log ("Request handler 'upload' was called .");
Response. writeHead (200, {"Content-Type": "text/plain "});
Response. write ("You 've sent the text:" + querystring. parse (postData). text );
Response. end ();
}
Exports. start = start;
Exports. upload = upload;

Well, the above is all about processing POST data.

Next, we will implement the image upload function.

Related Article

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.