---
title: "node http部分(一)"
author: "gleams"
date: "2014-06-25T14:17:40Z"
tags: []
categories: ["Web前端"]
slug: "node-http"
draft: false
lastmod: "2014-06-25T14:58:53Z"
id: 2084865
url: "https://gleams.iteye.com/blog/2084865"
---

学习node.js 有比较长的时候了，但没有实践过，现在从简单的知识点复习。

第一步：创建package.json 项目依赖文件

 

node.js不要被名字迷惑，他不是 javascript，但与js有很大的关联，语法基本一样。

 

使用http 就会用到http模块，看下面代码

```
var http = require('http');
http.createServer(function(req,res){
    res.writeHead(200);
    res.end('hello world!');

}).listen(3000);
console.log("服务启动:3000")
```

 打开浏览器输入 [http://localhost:3000/](http://localhost:3000/)

如果能在页面中看到 hello world!说明正常启动了。

 

在node.js需要明确定义头信息。（前端或许不太关注头信息，但后端人员会很关注头信息的，如果头信息不同传输的内容是不一样的。）上面的例子没有指定头信息，就会是一个普通的文本(text/plain)文件，不会做为html文件渲染，

 

如果是html需要指定头信息看下面代码：

```
var http = require('http');
http.createServer(function(req,res){
    res.writeHead(200,{'content-type':'text/html'});
    res.end('hello world!');

}).listen(3000);
console.log("服务启动:3000")
```

 

要想看到html标签的内容很简单，就是在字符中加入html标签就可以了。

 

```
var http = require('http');
http.createServer(function(req,res){
    res.writeHead(200,{'content-type':'text/html'});
    res.end('hello world!');

}).listen(3000);
console.log("服务启动:3000")
```

 其实上面的代码比较简单，node.js可以自己搭建一个http的服务器，不需要第三方的。

简单的代码中也需要注意：createServer(function(req,res){}) 这个函数中通过高阶函数把参数req,res加入到代码中，req,res是什么呢？

 

什么是高阶函数呢？

高阶函数（Higher Order Function）作为函数式编程众多风格中的一项显著特征，经常被使用着。按照[维基百科](http://zh.wikipedia.org/zh-sg/%E9%AB%98%E9%98%B6%E5%87%BD%E6%95%B0)上面的定义，高阶函数是至少满足下列一个条件的函数：

- 接受函数作为输入
- 输出一个函数

这两个req,res什么时候定义的呢？ 肯定是在定义createServer的时候已经定义了这个两个函数了，特别注意的是node.js是javascript的特性，所以不需要申明变量的类型，所以这个req,res看不出类型。

看看下面的小例子

```
function a(){



}
a.pr = function(){
  alert('a');
}


function b(fun){

  var bb = a;
  
  fun.call(null,bb);

}


b(function(c){
    c.pr();
});
```

 

函数b()把函数作为参数，在b()函数体内通过call调用，call调用的时候就可以指定参数。

 

http协议构建在请求和响应的概念上，对应在Node.js中就是http.ServerRequest和http.serverResponse这两个构造器构造出来的对象，而http.ServerRequest是IncomingMessage的实例。

所以查看Node.js帮助文档的时候实际上查看的是IncomingMessage-&gt;[http.IncomingMessage](http://nodeapi.ucdok.com/api/http.html#http_http_incomingmessage_16)和http.serverResponse

 

明白了这一点就能明白为什么会出现下面这种req.url（查看[http.IncomingMessage](http://nodeapi.ucdok.com/api/http.html#http_http_incomingmessage_16)的帮助就知道有这个属性）

```
var http = require('http');
http.createServer(function(req,res){
    res.writeHead(200,{'content-type':'text/html'});


    if(req.url == '/'){
        res.write('home');
    }

    if(req.url == '/savepage'){
        res.write('savepage')
    }

    res.end();



}).listen(3000);
console.log("服务启动:3000")
```

 

 启动服务后有两个地址可以访问 一个是/ 首页，另一个是/savepage

 

看一个简单的表单程序

 

```
var http = require('http');
http.createServer(function(req,res){
    res.writeHead(200,{'content-type':'text/html'});


    if(req.url == '/'){
        res.write('<meta charset="UTF-8">');
        res.end('<a href="/reg">注册</a>');
    }

    if(req.url == '/reg' ){
        res.end(['<!doctype html>',
                   '<meta charset="UTF-8"/>',
                   '<h1>用户注册</h1>',
                    '<form method="POST" action="/url">',
                    '<label>用户名：</label><input type="text" name="name"/>',
                    '<label>密码:</label><input type="password" name="password"/>',
                    ' <input type="submit" value="提交"/>  </form>'
        ].join(''));
    }


    if(req.url == '/url' && req.method == 'POST'){
       var body = '';

        req.on('data',function(chunk){
                body += chunk;

        });
        req.on('end',function(){
            res.write(['<!doctype html>',
                '<meta charset="UTF-8"/>',
                '<h1>注册信息是</h1>'].join(''));
            res.end(body);
        });
    }




}).listen(3000);
console.log("服务启动:3000")
```