Learning node (2) from 0 to 1 and building an http server

Source: Internet
Author: User
Tags html header node server
Learning node (2) from 0 to 1 and building an http server

During the course of the previous section, we learned about the connection and differences between different module specifications. In this section, we officially started learning about node. First, we started from setting up an http server and running simple programs.

1. hello world

Classichello world. First, createserver.jsTo save our code:

console.log( 'hello world' );

Enternode server.jsRun:

node server.js

The terminal will outputHello world. However, a node server program always needs to be accessed in a browser.httpModule:

Var http = require ('HTTP '); // introduce the http module // create an http server // request: request information from the browser // response: information returned from the server to the browser http. createServer (function (request, response) {response. writeHead (200, {'content-type': 'text/plain '}); // sets the header information and outputs the text response. write ('Hello World'); // The information output to the page response. end (); // return end }). listen (3000); console. log ('server has started... ');

We enternode server.jsRun, there will be output in the terminalServer has started...Indicates that the server has been created and is running, and then we access127.0.0.1:3000You can see the output on the page.hello world.

2. form

We just output a simple piece of text on the page. Now we want to present a form on the page, which allows users to input information and submit it:

// Server. jsvar http = require ('HTTP '); http. createServer (function (request, response) {var html ='\\
 \\\\\'; Response. writeHead (200, {'content-type': 'text/html'}); // outputs the html header information response. write (html); // output the spliced html string to response on the page. end (); // end }). listen (3000); console. log ('server has started... ');

Modify the content in server. js and run the following command again:

node server.js

After refreshing the page, we found that three text boxes and one submit button are output on the page. Because our program only renders the page and does not do any other processing, submitting data on the page only refreshes the current page.

Note:Every time we modify any code in node, We have to restart it.

2.1 GET the data submitted by form GET

The POST method is used in the above code, but we should first discuss the useGETWe do not consider data security first, but learn how to obtain the form data submitted using get, change post to get, and run it again.

We know that when we use get to submit data, it will pass the data as a URL parameter. Therefore, we get the data by parsing the parameters in the URL. Here we useurlMethods In the module:

// Server. jsvar http = require ('HTTP '), url = require ('url'); http. createServer (function (request, response) {var html ='\\
 \\\\\'; Var query = url. parse (request. url, true). query; if (query. submit) {var data ='

Back

'+'

Username: '+ query. username +'

'+'

Password: '+ query. password +'

'+'

Age: '+ query. age +'

'; Response. writeHead (200, {'content-type': 'text/html'}); response. write (data);} else {response. writeHead (200, {'content-type': 'text/html'}); response. write (html);} response. end (); // end }). listen (3000); console. log ('server has started... ');

After running the submit command again, the data will be displayed on the page.

Url. parse is used to parse the URL string and return the parsed URL object. If we only output url. parse (request. url ):

url.parse(request.url);result:Url {    protocol: null,        slashes: null,         auth: null,          host: null,          port: null,          hostname: null,          hash: null,          search: '?username=111113&password=123&age=122&submit=submit',          query: 'username=111113&password=123&age=122&submit=submit',          pathname: '/',           path: '/?username=111113&password=123&age=122&submit=submit',           href: '/?username=111113&password=123&age=122&submit=submit'       }

If 2nd parameters are set to true, the query attribute in the returned result is parsed as an object, and other attributes remain unchanged. The default value is false, that is, the query attribute is a string:

url.parse(request.url, true);result:Url {...query: {    username: '111113',    password: '123',    age: '122',    submit: 'submit' },...}

Therefore, we can use the following statement to determine whether data has been submitted and obtain the submitted data, and then output it to the center:

var query = url.parse( request.url, true ).query;/*{    username: '111113',    password: '123',    age: '122',    submit: 'submit'}*/

2.2 obtain data submitted in form POST Mode

Now we use the post method to submit data. Because POST requests are generally "heavy" (users may input a large amount of content), if you use a blocking method for processing, it will inevitably lead to user operation blocking. Therefore, node splits the post data into many small data blocks and then uses the data event (indicating that the new small data block has arrived) and end events pass these small data blocks (indicating that all data has been received ). Therefore, our idea should be: Get data blocks in the data event and operate data in the end event.

// server.jsvar http = require('http'),querystring = require('querystring');http.createServer(function(request, response){    var html = '\        \        
 \        \        \        \        \        ';        if( request.method.toLowerCase()=='post' ){        var postData = '';        request.addListener('data', function(chunk){            postData += chunk;        });        request.addListener('end', function(){            var data = querystring.parse(postData);            console.log( 'postData: '+postData );            console.log(data);                var s = '

back

'+ '

username:'+data.username+'

'+ '

password:'+data.password+'

'+ '

age:'+data.age+'

'; response.writeHead(200, {'content-type': 'text/html'}); response.write(s); response.end(); }) }else{ response.writeHead(200, {'content-type': 'text/html'}); response.write(html); response.end(); }}).listen(3000);console.log('server has started...');

The main changes between this code and the previous Code project are as follows:

  1. Instead of the url module, use the querystring module. Because we no longer perform URL operations and do not need to introduce them;

  2. Userequest.method.toLowerCase()=='post'Determines whether data is submitted;

  3. Concatenates data in a data event and processes it in an end event;

  4. response.end()Written inendIn the event, because the end event is an asynchronous operation, it must be output before execution.response.end()

We can see in the console that postData is such a string:

'username=123&password=123&age=23&submit=submit';

Therefore, we usequery.parseResolve postData to the object type to obtain the submitted data.

3. Routing

Now all our logic is implemented in the root directory, but it is not differentiated by url. Here we split the routes by function. For the above post request, we can split it into page initialization and form post-Submission processing.

Page initialization:

// Initialize function start (request, response) {var html = 'on the starter. js page'\\
 \\\\\'; Response. writeHead (200, {"Content-Type": "text/html"}); response. write (html); response. end ();} exports. start = start;

Display the obtained data:

// Uploader. js displays the obtained data var querystring = require ('querystring'); function upload (request, response) {var postData = ''; request. addListener ('data', function (chunk) {postData + = chunk;}); request. addListener ('end', function () {var data = querystring. parse (postData); console. log ('postdata: '+ postData); console. log (data); var s ='

Back

'+'

Username: '+ data. username +'

'+'

Password: '+ data. password +'

'+'

Age: '+ data. age +'

'; Response. writeHead (200, {'content-type': 'text/html'}); response. write (s); response. end () ;}} exports. upload = upload;

Then select routes in server. js

// server.jsvar http = require('http'),url = require('url');http.createServer(function(request, response){    var pathname = url.parse(request.url).pathname;    console.log(pathname);    response.end();}).listen(3000);console.log('server has started...');

If we change the URL address arbitrarily, we will see the pathname of each output address (ignore/favicon. ico ):

Http: // 127.0.0.1: 3000 // output:/http: // 127.0.0.1: 3000/show // output:/show/http: // 127.0.0.1: 3000/show/img // output:/show/img/http: // 127.0.0.1: 3000/show /? Username = wenzi // output:/show/

Therefore, we perform Routing Based on pathname and perform method ing on the route:

// server.jsvar http = require('http'),url = require('url'),starter = require('./starter'),uploader = require('./uploader');http.createServer(function(request, response){    var pathname = url.parse(request.url).pathname;    var routeurl = {        '/' : starter.start,        '/show' : uploader.upload    }    if( typeof routeurl[pathname]=== 'function' ){        routeurl[pathname](request, response);    }else{        console.log('404 not found!');        response.end();    }}).listen(3000);console.log('server has started...');

If a route is matched/, Execute starter. start (request, response );/show, Then run uploader. upload (request, response ). If none of them match, 404 is displayed.

4. Upload and display images

We have successfully submitted the data above. Here we will explain how to upload and display images. It is very troublesome to use the modules that come with node. Here we use the modules that have been developed by others.formidableModule, which abstracts the parsed file data.

npm install formidable --save-dev

In starter. js, we add the file control:

// starter.jsfunction start(request, response){    var html = '\        \        
 \        \        \        \        \        ';    response.writeHead(200, {"Content-Type":"text/html"});    response.write( html );    response.end();}exports.start = start;
4.1 upload images

First, we need to upload images. First, we need to ensure that the tmp and img directories exist in the current directory. In uploader. js:

// Uploader. jsvar formidable = require ('formidable'), util = require ('util'), fs = require ('fs'); function upload (request, response) {if (request. method. toLowerCase () = 'post') {var form = new formidable. incomingForm (); form. uploadDir = '. /tmp/'; form. parse (request, function (err, fields, files) {var oldname = files. upload. name, newname = Date. now () + oldname. substr (oldname. lastIndexOf ('. '); fs. renameSync (files. upload. path ,". /img/"+ newname); // upload to the img directory response. writeHead (200, {'content-type': 'text/plain '}); response. write ('stored ed upload: \ n \ n'); response. end (util. inspect ({fields: fields, files: files}) ;}); return ;}} exports. upload = upload;

After uploading the image, we will jump to the upload path and display the corresponding information:

Stored ed upload: {fields: {// other controls, such as input, textarea, and other submit: 'submit '}, files: {// file control upload: {domain: null, _ events :{}, _ maxListeners: undefined, size: 5097, path: 'tmp \ upload', name: 'chrome.png ', type: 'image/png', hash: null, lastModifiedDate: Thu Jan 12 2017 23:09:50 GMT + 0800 (China Standard Time), _ writeStream: [Object] }}

When we look at the img directory, we will find the photo we just uploaded.

4.2 Image Display

After uploading images to the server, how can I display the images in a browser. Here we usefsModule to read files and createshower.jsTo display images:

// Shower. jsvar fs = require ('fs'), url = require ('url'); function show (request, response) {var query = url. parse (request. url, true ). query, imgurl = query. src; // read the image and output it. // read the src parameter in the link to specify which image to read/show? Src00001484211660592.png fs. readFile ('. /img/'+ imgurl, "binary", function (err, file) {if (err) throw err; response. writeHead (200, {"Content-Type": "image/png"}); response. write (file, "binary"); response. end () ;}} exports. show = show;

Then add the show route ing in server. js:

Var routeurl = {'/': starter. start, '/upload': uploader. upload,'/show': shower. show // Add };


Finally, reference the image in upload. js:

Form. parse (request, function (err, fields, files) {var oldname = files. upload. name, newname = Date. now () + oldname. substr (oldname. lastIndexOf ('. '); fs. renameSync (files. upload. path ,". /img/"+ newname); // synchronously upload the image response. writeHead (200, {'content-type': 'text/html'}); var s ='

Back

'; // Display the image response. write (s); response. end ();});

5. Comprehensive

I have just learned how to upload data and images. Here we will combine them and draw up a question: "set the user name and password and upload the Avatar ". I hope you can implement it by yourself.

6. Interface implementation

After learning GET and POST requests in Part 2, it is not difficult to write a simple json or jsonp interface here.

Create an inter. js:

// inter.jsvar url = require('url');function init(request, response){    if( request.method.toLowerCase()=='get' ){        var query = url.parse(request.url, true).query;        var data = {"code":0, "msg":"success", "data":[{"username":"wenzi", "age":26}, {"username":"bing", "age":25}]};        if( query && query.callback ){            // jsonp            response.end( query.callback + '(' + JSON.stringify(data) + ')' );         }else{            // json            response.end( JSON.stringify(data) );        }    }}exports.init = init;

Add inter reference and route ing to server:

Var routeurl = {'/': starter. start, '/upload': uploader. upload, '/show': shower. show, '/inter': inter. init // Add };

Thenhttp://127.0.0.1:3000/interPerform a json request or a jsonp request.

7. Summary

I wrote a lot in this section. The core of this section is to explain how to set up a simple http server to submit and process data and images. At last, I briefly wrote the interface, if you have the opportunity later, we will explain the compilation of interfaces in detail.


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.