Easily create Nodejs servers (10): Process Post Requests _node.js

Source: Internet
Author: User
Tags http request require

So far, the server we're doing has no real use, and then we're going to start implementing some of the actually useful features.

What we want to do is: The user selects a file, uploads the file, and then sees the uploaded file in the browser.

First we need a text area (textarea) for the user to enter the content and then submit it to the server via a POST request.

We add the code to the start event handler, and the Requesthandlers.js is modified as follows:

Copy Code code as follows:



function Start (response) {


Console.log ("Request handler ' start ' was called.");


var body = ' <html> ' + ' <head> ' +


"<meta http-equiv=" Content-type "content=" text/html; '+


' Charset=utf-8 '/> ' +


' </head> ' +


' <body> ' +


' <form action= '/upload ' method= ' post ' > ' +


' <textarea name= ' text ' rows= ' cols= ' ></textarea> ' +


' <input type= ' submit ' value= ' submit text '/> ' +


' </form> ' +


' </body> ' +


' </html> ';


Response.writehead ({"Content-type": "Text/html"});


Response.Write (body);


Response.End ();


}


function upload (response) {


Console.log ("Request handler ' upload ' was called.");


Response.writehead ({"Content-type": "Text/plain"});


Response.Write ("Hello Upload");


Response.End ();


}


Exports.start = start;


Exports.upload = upload;


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

Next we want to implement when the user submits the form, triggering the/upload request handler to process the POST request.

To make the entire process non-blocking, Node.js splits the post data into small chunks of data and then passes the small blocks of data to the callback function by triggering a specific event. The specific event here has a data event (representing the arrival of a new small block of data) and an end event (indicating that all data has been received).

We implement this by registering the Listener (listener) on the request object. The request object here is that each time an HTTP request is received, the object is passed to the ONrequest callback function.

We put the code on the server and server.js the following changes:

Copy Code code 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 up the code format for receiving the data as UTF-8, then register the listener for the "data" event to collect the new block of data received each time and assign it to the PostData variable, and finally we move the call to the request route to the end event handler To ensure that it is triggered only once all data has been received, and only once. We also pass the post data to the request route because the data is used by the request handler.

Next on the/upload page, show the user input

Let's change the router.js:

Copy Code code 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 Code code as follows:



function Start (response, PostData) {


Console.log ("Request handler ' start ' was called.");


var body = ' <html> ' +


' <head> ' +


"<meta http-equiv=" Content-type "content=" text/html; '+


' Charset=utf-8 '/> ' +


' </head> ' +


' <body> ' +


' <form action= '/upload ' method= ' post ' > ' +


' <textarea name= ' text ' rows= ' cols= ' ></textarea> ' +


' <input type= ' submit ' value= ' submit text '/> ' +


' </form> ' +


' </body> ' +


' </html> ';


Response.writehead ({"Content-type": "Text/html"});


Response.Write (body);


Response.End ();


}


function upload (response, postdata) {


Console.log ("Request handler ' upload ' was called.");


Response.writehead ({"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 handler. We should only pass the post data to the request route and request handler for the part of which we are interested. In our case, we're interested in actually just the text field.

We can use the QueryString module described earlier to implement:

Copy Code code as follows:



var querystring = require ("querystring");


function Start (response, PostData) {


Console.log ("Request handler ' start ' was called.");


var body = ' <html> ' +


' <head> ' +


"<meta http-equiv=" Content-type "content=" text/html; '+


' Charset=utf-8 '/> ' +


' </head> ' +


' <body> ' +


' <form action= '/upload ' method= ' post ' > ' +


' <textarea name= ' text ' rows= ' cols= ' ></textarea> ' +


' <input type= ' submit ' value= ' submit text '/> ' +


' </form> ' +


' </body> ' +


' </html> ';


Response.writehead ({"Content-type": "Text/html"});


Response.Write (body);


Response.End ();


}


function upload (response, postdata) {


Console.log ("Request handler ' upload ' was called.");


Response.writehead ({"Content-type": "Text/plain"});


Response.Write ("You ' ve sent the text:" + querystring.parse (postdata). Text);


Response.End ();


}


Exports.start = start;


Exports.upload = upload;


Well, that's all about processing post data.

In the next section, we will implement the image upload function.

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.