Home  >  Article  >  Web Front-end  >  Learn node from 0 to 1 (2) to build an http server

Learn node from 0 to 1 (2) to build an http server

大家讲道理
大家讲道理Original
2017-01-24 15:40:401126browse

In the previous pre-class study, we learned about the connections and differences between different module specifications. In this section, we officially start learning node. First, we start by building an http server that can run simple programs.

1. hello world

The most classic hello world. First we create a server.js to save our code:

console.log( 'hello world' );

Enter node server.js in the terminal to run:

node server.js

The terminal will output the words hello world. But our node server program always needs to be accessed on the browser. Here we need to use the http module that comes with node:

var http = require('http'); // 引入http模块// 创建http服务器// request : 从浏览器带来的请求信息// response : 从服务器返回给浏览器的信息http.createServer(function(request, response){
    response.writeHead(200, {'content-type': 'text/plain'}); // 设置头部信息,输出text文本
    response.write('hello world'); // 输出到页面中的信息
    response.end(); // 返回结束}).listen(3000);console.log('server has started...');

We enter node server.js in the terminal again to run. There will be output in the terminal server has started..., indicating that the server has been created and is running. Then we run on the browser Visit 127.0.0.1:3000, and you can see hello world output on the page.

2. form form

Just now we just output a simple text on the page, now we want to present a form on the page that allows users to enter information and submit:

// server.js
var http = require('http');

http.createServer(function(request, response){
var html = &#39;<html>\    <head>\    <meta charset=UTF-8" />\    </head>\    <body>\    <form action="/" method="post">\    <p>username : <input type="text" name="username" /></p>\    <p>password : <input type="password" name="password" /></p>\    <p>age : <input type="text" name="age" /></p>\    <p><input type="submit" value="submit" name="submit" /></p>\    </form>\    </body>\    </html>&#39;;

    response.writeHead(200, {&#39;content-type&#39;: &#39;text/html&#39;}); // 输出html头信息
    response.write(html); // 将拼接的html字符串输出到页面中
    response.end(); // 结束
}).listen(3000);
console.log(&#39;server has started...&#39;);

Modify the content in server.js and re-run:

node server.js

After refreshing the page, we found that 3 text boxes and 1 submit button. Because our program only renders the page and does not do any other processing, submitting data in the page just refreshes the current page.

Note: Every time we modify any code in node, we must restart it.

2.1 Get the data submitted by the form GET method

We use the POST method in the above code, but here we need to discuss the data submitted using the GET method first. Let's not consider the security of the data first, but just learn how to obtain the form data submitted using the get method, change post to get, and run again.

We know that using the get method to submit data will pass the data as URL parameters, so we obtain the data by parsing the parameters in the URL. Here we use the url module Method:

// server.js
var http = require(&#39;http&#39;),
url = require(&#39;url&#39;);

http.createServer(function(request, response){
    var html = &#39;<html>\        <head>\        <meta charset=UTF-8" />\        </head>\        <body>\        <form action="/" method="get">\        <p>username : <input type="text" name="username" /></p>\        <p>password : <input type="password" name="password" /></p>\        <p>age : <input type="text" name="age" /></p>\        <p><input type="submit" value="submit" name="submit" /></p>\        </form>\        </body>\        </html>&#39;;
    
    var query = url.parse( request.url, true ).query;
    if( query.submit ){
        var data = &#39;<p><a href="/">back</a></p>&#39;+
            &#39;<p>username:&#39;+query.username+&#39;</p>&#39;+
            &#39;<p>password:&#39;+query.password+&#39;</p>&#39;+
            &#39;<p>age:&#39;+query.age+&#39;</p>&#39;;
         
        response.writeHead(200, {&#39;content-type&#39;: &#39;text/html&#39;});
        response.write(data);
    }else{
        response.writeHead(200, {&#39;content-type&#39;: &#39;text/html&#39;});
        response.write(html);
    }
    response.end(); // 结束
}).listen(3000);
console.log(&#39;server has started...&#39;);

After we run the submission again, the data will be displayed on the page.

url.parse is used to parse URL strings 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: &#39;?username=111113&password=123&age=122&submit=submit&#39;,    
      query: &#39;username=111113&password=123&age=122&submit=submit&#39;,   
       pathname: &#39;/&#39;,    
       path: &#39;/?username=111113&password=123&age=122&submit=submit&#39;,    
       href: &#39;/?username=111113&password=123&age=122&submit=submit&#39;
       }

If the second parameter is set to true, the query attribute in the returned result will be parsed into an object, and other attributes will remain unchanged; The default value is false, that is, the query attribute is a string:

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

Therefore, we can use the following statement to determine whether there is submitted data and obtain the submitted data, and then output it to:

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

2.2 Get the data submitted by the form POST method

Now we use the post method to submit the data. Because POST requests are generally "heavy" (users may enter a large amount of content), if they are processed in a blocking manner, it will inevitably lead to blocking of user operations. Therefore, node splits the post data into many small data blocks, and then delivers these small data blocks through the data event (indicating that new small data blocks have arrived) and the end event (indicating that all data has been received). Therefore, our idea should be: obtain the data block in the data event and operate the data in the end event.

// server.js
var http = require(&#39;http&#39;),
querystring = require(&#39;querystring&#39;);

http.createServer(function(request, response){
    var html = &#39;<html>\        <head>\        <meta charset=UTF-8" />\        </head>\        <body>\        <form action="/" method="post">\        <p>username : <input type="text" name="username" /></p>\        <p>password : <input type="password" name="password" /></p>\        <p>age : <input type="text" name="age" /></p>\        <p><input type="submit" value="submit" name="submit" /></p>\        </form>\        </body>\        </html>&#39;;
    
    if( request.method.toLowerCase()==&#39;post&#39; ){
        var postData = &#39;&#39;;

        request.addListener(&#39;data&#39;, function(chunk){
            postData += chunk;
        });

        request.addListener(&#39;end&#39;, function(){
            var data = querystring.parse(postData);
            console.log( &#39;postData: &#39;+postData );
            console.log(data);
    
            var s = &#39;<p><a href="/">back</a></p>&#39;+
                &#39;<p>username:&#39;+data.username+&#39;</p>&#39;+
                &#39;<p>password:&#39;+data.password+&#39;</p>&#39;+
                &#39;<p>age:&#39;+data.age+&#39;</p>&#39;;

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

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

  1. No longer introduce the url module, use the import instead querystring module. Because we no longer operate the URL, there is no need to introduce it;

  2. Use request.method.toLowerCase()=='post' to determine whether the current There is data submission;

  3. The data is spliced ​​in the data event and processed in the end event;

  4. response.end () is written inside the end event. Because the end event is an asynchronous operation, it must be executed after the data output is completed. response.end()

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

&#39;username=123&password=123&age=23&submit=submit&#39;;

因此我们使用query.parse将postData解析为对象类型,以便获取提交过来的数据。

3. 路由

现在我们所有的逻辑都是在根目录下进行的,没有按照url区分,这里我们按照功能进行路由拆分。以上面的post请求为例,我们可以拆分为:页面初始化和form提交后的处理。

页面初始化:

// starter.js  页面初始化

function start(request, response){
    var html = &#39;<html>\        <head>\        <meta charset=UTF-8" />\        </head>\        <body>\        <form action="/show" method="post">\        <p>username : <input type="text" name="username" /></p>\        <p>password : <input type="password" name="password" /></p>\        <p>age : <input type="text" name="age" /></p>\        <p><input type="submit" value="submit" name="submit" /></p>\        </form>\        </body>\        </html>&#39;;
    
    response.writeHead(200, {"Content-Type":"text/html"});
    response.write( html );
    response.end();
}
exports.start = start;

展示获取的数据:

// uploader.js 展示获取的数据var querystring = require(&#39;querystring&#39;);function upload(request, response){    var postData = &#39;&#39;;

    request.addListener(&#39;data&#39;, function(chunk){
      postData += chunk;
    });
    
    request.addListener(&#39;end&#39;, function(){        var data = querystring.parse(postData);        console.log( &#39;postData: &#39;+postData );        console.log(data);        var s = &#39;<p><a href="/">back</a></p>&#39;+            &#39;<p>username:&#39;+data.username+&#39;</p>&#39;+            &#39;<p>password:&#39;+data.password+&#39;</p>&#39;+            &#39;<p>age:&#39;+data.age+&#39;</p>&#39;;

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

然后在server.js中进行路由选择

// server.jsvar http = require(&#39;http&#39;),
url = require(&#39;url&#39;);

http.createServer(function(request, response){    var pathname = url.parse(request.url).pathname;    console.log(pathname);
    response.end();
}).listen(3000);console.log(&#39;server has started...&#39;);

我们任意改变URL地址,会看到输出的每个地址的pathname(忽略/favicon.ico):

http://127.0.0.1:3000/ // 输出: /
http://127.0.0.1:3000/show/ // 输出: /show/
http://127.0.0.1:3000/show/img/ // 输出: /show/img/
http://127.0.0.1:3000/show/?username=wenzi // 输出: /show/

因此我们就根据pathname进行路由,对路由进行方法映射:

// server.jsvar http = require(&#39;http&#39;),
url = require(&#39;url&#39;),
starter = require(&#39;./starter&#39;),
uploader = require(&#39;./uploader&#39;);

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

如果匹配到路由 / ,则执行 starter.start(request, response) ;如果匹配到路由 /show ,则执行 uploader.upload(request, response) 。如果都没匹配到,则显示404。

4. 图片上传并显示

在上面我们已经能成功提交数据了,这里来讲解如何进行图片上传并显示。使用node自带的模块处理起来非常的麻烦,这里我们使用别人已经开发好的formidable模块进行编写,它对解析上传的文件数据做了很好的抽象。

npm install formidable --save-dev

在starter.js中,我们添加上file控件:

// starter.js
function start(request, response){
    var html = &#39;<html>\
        <head>\
        <meta charset=UTF-8" />\
        </head>\
        <body>\
        <form action="/upload" method="post" enctype="multipart/form-data">\
        <p>file : <input type="file" name="upload" multiple="multiple" /></p>\
        <p><input type="submit" value="submit" name="submit" /></p>\
        </form>\
        </body>\
        </html>&#39;;
    response.writeHead(200, {"Content-Type":"text/html"});
    response.write( html );
    response.end();
}
exports.start = start;

4.1 图片上传

首先我们进行的是图片上传操作,首先我们要确保当前目录中存在tmp和img目录。在 uploader.js 中:

// uploader.jsvar formidable = require(&#39;formidable&#39;),
util = require(&#39;util&#39;),
fs = require(&#39;fs&#39;);function upload(request, response){    if( request.method.toLowerCase()==&#39;post&#39; ){        var form = new formidable.IncomingForm();

        form.uploadDir = &#39;./tmp/&#39;;
        form.parse(request, function(err, fields, files) {            var oldname = files.upload.name,
                newname = Date.now() + oldname.substr(oldname.lastIndexOf(&#39;.&#39;));
            fs.renameSync(files.upload.path, "./img/"+newname ); // 上传到 img 目录

            response.writeHead(200, {&#39;content-type&#39;: &#39;text/plain&#39;});
            response.write(&#39;received upload:\n\n&#39;);
            response.end(util.inspect({fields: fields, files: files}));
        });        return;
    }
}
exports.upload = upload;

我们上传图片后跳转到upload路径,然后显示出相应的信息:

received upload:

{
    fields: { // 其他控件,如input, textarea等
    submit: &#39;submit&#39;},
files:{ // file控件
    upload:{
            domain: null,
            _events: {},
            _maxListeners: undefined,
            size: 5097,
            path: &#39;tmp\\upload_b1f7c3e83af224e9f3a020958cde5dcd&#39;,
            name: &#39;chrome.png&#39;,
            type: &#39;image/png&#39;,
            hash: null,
            lastModifiedDate: Thu Jan 12 2017 23:09:50 GMT+0800 (中国标准时间),
            _writeStream: [Object]
        }
    }
}

我们再查看img目录时,就会发现我们刚才上传的照片了。

4.2 图片显示

将图片上传到服务器后,怎样才能把图片显示在浏览器上呢。这里我们就使用到了fs模块来读取文件,创建一个shower.js来专门展示图片:

// shower.jsvar fs = require(&#39;fs&#39;),
url = require(&#39;url&#39;);function show(request, response){    var query = url.parse(request.url, true).query,
        imgurl = query.src;    // 读取图片并进行输出
    // 这里读取链接中的src参数,指定读取哪张图片  /show?src=1484234660592.png
    fs.readFile(&#39;./img/&#39;+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;

然后在 server.js 中添加上 show 的路由映射:

var routeurl = {  
  &#39;/&#39; : starter.start,   
   &#39;/upload&#39; : uploader.upload,  
   &#39;/show&#39; : shower.show 
   // 添加
   };


最后在 upload.js 中进行图片的引用:

form.parse(request, function(err, fields, files) {    var oldname = files.upload.name,
        newname = Date.now() + oldname.substr(oldname.lastIndexOf(&#39;.&#39;));
    fs.renameSync(files.upload.path, "./img/"+newname ); // 同步上传图片

    response.writeHead(200, {&#39;content-type&#39;: &#39;text/html&#39;});    var s = &#39;<p><a href="/">back</a></p><p><img src="/show?src=&#39;+newname+&#39;" /></p>&#39;; // 显示刚才的图片
    response.write(s);
    response.end();
});

5. 综合

刚才学习了上传数据和上传图片,这里我们将其综合一下,拟定一个题目:“设定用户名密码,并上传头像”。希望可以自己实现一下。

6. 接口的实现

在第2部分学习了GET和POST请求,那么在这里写一个简单json或jsonp接口应该不是什么难事儿了吧。

创建一个 inter.js :

// inter.jsvar url = require(&#39;url&#39;);function init(request, response){    if( request.method.toLowerCase()==&#39;get&#39; ){        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 + &#39;(&#39; + JSON.stringify(data) + &#39;)&#39; );
         }else{            // json
            response.end( JSON.stringify(data) );
        }
    }
}
exports.init = init;

在server中添加inter的引用和路由映射:

var routeurl = {    &#39;/&#39; : starter.start,    &#39;/upload&#39; : uploader.upload,    &#39;/show&#39; : shower.show,    &#39;/inter&#39; : inter.init // 添加};

然后对 http://127.0.0.1:3000/inter 进行json请求或jsonp请求即可。

7. 总结

这节还是写了不少的内容,最核心的就是讲解如何搭建一个简单的http服务器,进行数据和图片的提交与处理,在最后稍微讲了下接口的编写,后面有机会的话,会再具体讲解下接口的编写。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn