---
title: "nodejs-http服务"
author: "devil13th"
date: "2015-12-09T18:48:01Z"
tags: []
categories: ["互联网"]
slug: "nodejs-http"
draft: false
lastmod: "2015-12-09T19:05:31Z"
id: 2262986
url: "https://devil13th.iteye.com/blog/2262986"
---

使用nodejs搭建http服务很简单，代码如下：

```
var http = require("http");//获取http对象
http.createServer(
  //匿名的回调函数，当有请求进来的时候调用该函数
  //req参数相当于J2EE的HttpServletRequest,
  //res参数相当于J2EE的HttpServletResponse
  function(req,res){
    console.log("run ... ");
    res.writeHead(200,{'Content-Type':'text/html'});//响应代码为200（正常） 已html方式展示
    res.write("<h1>Hello World</h3>"); //输出html代码
    res.end('<p>hello World</p>');//输出html代码，必须要调用res.end()方法，否则浏览器一直等待直到该方法调用
  }
).listen(3000); //监听3000端口

console.log(" HTTP Server is Listening at port 3000.");
```

 打开浏览器输入[http://127.0.0.1:3000/](http://127.0.0.1:3000/%E5%90%8E%E5%9B%9E%E8%BD%A6%E5%8D%B3%E5%8F%AF%E7%9C%8B%E5%88%B0%E7%95%8C%E9%9D%A2)后回车即可看到界面

![](http://dl2.iteye.com/upload/attachment/0113/6631/a0355824-349f-3127-b107-7af1d49af9ee.png)

 

接下来对上面的代码进行改造：

```
var http = require("http");//获取http对象
var fs = require("fs"); //获取fs对象
http.createServer(
  //匿名的回调函数，当有请求进来的时候调用该函数
  //req参数相当于J2EE的HttpServletRequest,
  //res参数相当于J2EE的HttpServletResponse
  function(req,res){
    console.log("run ... ");
    res.writeHead(200,{'Content-Type':'text/html'});//响应代码为200（正常） 已html方式展示
  
	//异步读取数据
	fs.readFile("app02.html","utf-8",function(err,data){
		if(err){//如果出现错误则直接显示错误原因
			res.end(err);
		}else{//如果成功读取文件则返回文件内容
			res.end(data.toString());
		}
	});


  }
).listen(3000); //监听3000端口

console.log(" HTTP Server is Listening at port 3000.");
```

  打开浏览器输入[http://127.0.0.1:3000/](http://127.0.0.1:3000/%E5%90%8E%E5%9B%9E%E8%BD%A6%E5%8D%B3%E5%8F%AF%E7%9C%8B%E5%88%B0%E7%95%8C%E9%9D%A2)后回车即可看到界面

![](http://dl2.iteye.com/upload/attachment/0113/6638/80e2bfef-fd2c-394d-8923-5cb46578eef0.png)