node. JS Learning (2)-routing features and form uploads

Source: Internet
Author: User
Tags php language

Today, starting with the book "node. js", I learned some of the basics of node, including the creation of servers, the implementation of routing functions, forms uploading and data processing, and the feeling that I was beginning to understand some of the basic principles of node. js. This book is very detailed and very basic, it is suitable for beginners to learn. node. JS Getting Started

As we all know, node is different from the PHP language, and node doesn't need to rely on servers like Apache, because node itself can build the server! So before we use node to develop a website, we first have to learn how to build a server. About node creation server in my previous blog has been introduced, here no longer repeat.

Complete a form upload and data processing demo

1. Clear function, first determine which files need to be established ( because just demo, we do not need to write HTML files, involving the front-end of the simple processing is good.) )

Server file Server.js, program entry file index.js; routing file router.js; request processing File Handlerequest.js

First, we'll write the entry file:

<span style= "FONT-SIZE:18PX;" >var server= require ("./server.js");//introduce Server.jsvar router = require ("./router.js"); var handle = require ("./ Requesthandlers "), VAR handles ={};//associative array is used to transfer functions. handles["/"] = handle.start;//here is mainly for the following routing function, the user access Localhost:3000/start will go directly to the Start method handles["/start"] = Handle.start ; handles["/upload"] = Handle.upload;server.start (router.route,handles);</span>

Inside the index file, we initialize an associative array to hold the functions that need to be used. and turn on the server.

Server file:

<span style= "FONT-SIZE:18PX;" >var  http = require ("http");//node.js comes with an 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/when a user tries to access localhost:8888 Favicon.ico, remove this access result if (Req.url = = '/favicon.ico ') {return;} var postdata = ""; var pathname =  url.parse (req.url). pathname;//resolves the path name inside the URL req.setencoding ("UTF8"); Req.addlistener ("Data", function (postdatachunk) {//Get post data via callback function PostData + = Postdatachunk;}); Req.addlistener ("End", function () {route (handles,pathname,res,postdata);}); Console.log ("Requset" +pathname+ "arrived!");}). Listen (3000);//Listen for 3000 port number Console.log ("HTTP server has started!");}  Write the code in the server in a start function. And the function is exported, one time to complete the modularization of the code, in the remaining files only need to be in the   form of var  http = require ("http") to call; Exports.start = start;</span>

First, we set the encoded format of the received data to 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 make sure it only fires when all data is received and fires only once. We also pass the POST data to the request route, as this data is used by the request handler. to make the whole process non-blocking, node. js splits the post data into small chunks of data these small blocks of data are then passed to the callback function by triggering a specific event. The specific event here has a data event (indicating that a new small chunk of data has arrived) and an end event (indicating that all the data has been received).  

Router.js:

<span style= "FONT-SIZE:18PX;" >function Route (handles,pathname,res,postdata) {Console.log ("about-route a request to" +pathname); if (typeof Handles[pathname] = = = ' function ') {///through the judgment of the path name, call the corresponding function for processing, this is the basic idea of routing. Handles[pathname] (res,postdata);} Else{console.log ("No request handler found for" + pathname);}} Exports.route=route;</span>

The route function passes three parameters, the associative array handles (the function that holds the requesthandlers), the pathname is the access path, the res is the response object, and the PostData is the array that the post receives.

Requesthandles.js

var querystring = Require ("querystring"); function start (res) {var body = ' 
In this page, the start function first sends a Web page to the user, including the input box and button, the user input text Click Submit, the data is passed into the upload file and displayed. The upload file is used for display.






node. JS Learning (2)-routing features and form uploads

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.