Practice case a form submission
Demo.html
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <title>Form submission</title>5 </Head>6 <Body>7 <formMethod= "POST"Action= "Http://localhost:3000/">8Name:<inputtype= "text"name= "title" /><BR/><BR/><BR/>9Note:<textareaname= "text"></textarea><BR/>Ten <inputtype= "Submit"/> One </form> A </Body> - </HTML>
Postdata.js
1 //Post Form2 3 varHTTP = require (' http ');4 varQueryString = Require (' querystring '));5 6 varServer = Http.createserver (function(req,res) {7 varPost = ';8 9Req.on (' Data ',function(chunk) {TenPost + =Chunk; One }); A -Req.on (' End ',function(){ -Post =Querystring.parse (POST); the - Res.write (post.title); - Res.write (post.text); - res.end (); + }); -}). Listen (3000);
When running JS using the DOS window, remember to http,querystring two modules using NPM install-g xxx to Local.
CD to the above file directory, run the command
Node Postdata.js
Run
Submission Results Display Interface
Think: Php Gets the post-submitted data and returns the data to the user, writing only two lines of code,
echo $_post[' title ';
echo $_get[' text '];
node. js does this by creating an HTTP instance, manually writing an event listener for the Req object, and when the client data arrives, temporarily closing the post data into a closed variable until the end event fires, parsing the post request, and returning to the client after processing. PHP is simple because it encapsulates these features and provides only a high-level interface. Although the example here is directly using the HTTP module, but it is not let you use the module for Web development, the HTTP module is just an HTTP server kernel encapsulation, you can use it to do anything HTTP server can do, not just to do a website, Even implement an HTTP proxy server. If you develop a website directly using this method, you must implement everything manually.
Express Framework for a lightweight web framework
NPM offers a large number of third-party modules, with Express as the development framework and the most stable and widely used framework available today.
In addition to providing higher-level interfaces for HTTP modules, Express (http://expressjs.com/) also implements a number of features, including: Routing control, template parsing support, dynamic view, user session, CSRF protection, static file service, error controller, access log , caching, plug-in support, and so on, most of the functionality is only used in the HTTP protocol common operation encapsulation, more functions need plug-ins or integration of other modules to complete.
Implement the same example as before.
var express = require (' Express '); var app = express.createserver (); App.use (Express.bodyparser ()); App.all ('/',function (req,res) { res.send (req.body.title+req.body.text);}); App.listen (3000);
node. JS Practice First Day