Node. js Learning (2) -- routing and form upload

Source: Internet
Author: User

Node. js Learning (2) -- routing and form upload

Today. getting started with js this book has learned some basic knowledge about node, including server creation, implementation of routing functions, form upload and data processing. some basic principles of js. This book is very detailed and basic and suitable for beginners to learn. Getting started with node. js

As we all know, node is different from php. node does not need to depend on servers such as apache, because node itself can build servers! Therefore, before using node to develop websites, we must first learn how to build servers. I have already introduced how to create a server for node in my previous blog. I will not go into details here.

Complete a demo of form upload and Data Processing

1. Define the functions. First, determine the files to be created (because it is only a demo, we do not need to write html files, it is good to involve simple front-end processing .)

Server File server. js; program entry file index. js; route file router. js; request processing file handleRequest. js

First, write the entry file:

Var server = require (". /server. js "); // introduce server. jsvar router = require (". /router. js "); var handle = require (". /requestHandlers "); var handles ={}; // The associated array is used to pass functions. Handles ["/"] = handle. start; // This is mainly for later routing functions. When you access localhost: 3000/start, it will be directly transferred to the start method handles ["/start"] = handle. start; handles ["/upload"] = handle. upload; server. start (router. route, handles );

In the index file, we Initialize an associated array to store the required functions. And enable the server.

Server File:

Var http = require ("http"); // node. js built-in http module var url = require ("url"); function start (route, handles) {// create an HTTP server; http. createServer (function (req, res) {// anonymous function // Most servers access localhost: 8888/favicon when you try to access localhost: 8888. ico. Remove the access result if (req. url = '/favicon. ico ') {return;} var postData = ""; var pathname = url. parse (req. url ). pathname; // parse the url path req. setEncoding ("utf8"); req. addListener ("data", function (PostDataChunk) {// obtain post data using the callback function. postData ++ = postDataChunk;}); req. addListener ("end", function () {route (handles, pathname, res, postData) ;}); console. log ("Requset" + pathname + "arrived! ") ;}). Listen (3000); // listen to the 3000 port number console. log (" HTTP server has started! ") ;}// Write the server code in a start function. Export the function to modularize the code at one time. In other files, you only need to call the function in the form of var http = require ("http"); exports. start = start;

First, we set the encoding format of the received data to UTF-8, and then registered the listener for the "data" event to collect the new data block each time it was received, 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. 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 ).

Router. js:

Function route (handles, pathname, res, postData) {console. log ("About to route a request to" + pathname); if (typeof handles [pathname] = 'function') {// you can determine the path name, calling corresponding functions for processing is the basic idea of routing. Handles [pathname] (res, postData);} else {console. log ("No request handler found for" + pathname) ;}} exports. route = route;

The route function passes three parameters and associates the array handles (stores the functions in requestHandlers). pathname indicates the access path, res indicates the response object, and postData indicates the array received by post.

RequestHandles. js

var  querystring = require("querystring");function start(res){var body =  ''+     ''+     '
 '+     ''+     ''+     ''+     ''+     ''; console.log("Request Handlers for 'start' was called");res.writeHead(200,{"Content-Type":"text/html"});res.write(body);res.end();}function upload(res,postData){res.writeHead(200,{"Content-Type":"text/plain"});var temp_data = querystring.parse(postData).text;res.write(temp_data);res.end();console.log("Reques Handlers for 'upload ' was called");}exports.start = start;exports.upload = upload;
In this page, the start function first sends a webpage to the user, including the input box and button. The user inputs the text and clicks submit. The data is passed into the upload File and displayed. The upload file is used for display.






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.