您的位置:首页 > 理论基础 > 计算机网络

node.js模块学习(三) http

2017-11-23 14:41 579 查看
     http服务器

要开发HTTP服务器程序,从头处理TCP连接,解析HTTP是不现实的。这些工作实际上已经由Node.js自带的http模块完成了。应用程序并不直接和HTTP协议打交道,而是操作http模块提供的request和response对象。

request对象封装了HTTP请求,我们调用request对象的属性和方法就可以拿到所有HTTP请求的信息;

response对象封装了HTTP响应,我们操作response对象的方法,就可以把HTTP响应返回给浏览器。

用Node.js实现一个HTTP服务器程序非常简单。我们来实现一个最简单的Web程序hello.js,它对于所有请求,都返回Hello world!

'use strict';
//获得http模块
var http = require('http');
//创建httpserver,获取request,rsponse
var helloServer =  http.createServer(function(request,response){
console.log(request.method+","+request.url);
response.writeHead(200,{'Content-Type':'text/html'});
response.end('<h1>hello world</h1>');
});
helloServer.listen(8080);
console.log('server is running ');

         搭建文件服务器

让我们继续扩展一下上面的Web程序。我们可以设定一个目录,然后让Web程序变成一个文件服务器。要实现这一点,我们只需要解析
request.url
中的路径,然后在本地找到对应的文件,把文件内容发送出去就可以了。

解析URL需要用到Node.js提供的
url
模块,它使用起来非常简单,通过
parse()
将一个字符串解析为一个
Url
对象

          其实就是url输入文件路径,然后服务器会写文件内容

'use strice';
//获取url模块,解析文件路径
var fs = require('fs'),
url = require('url'),
path = require('path'),
http = require('http');
var workpath = path.resolve('.');
var fileserver = http.createServer(function (request,response) {
var pathname = url.parse(request.url).pathname;
console.log(pathname);
var filepath = path.join(workpath,pathname);
fs.stat(filepath,function(err,stats){
if(!err&&stats.isFile()){
//文件存在
console.log('200,文件存在');
response.writeHead(200,'content-type:text/html');
fs.createReadStream(filepath).pipe(response);
}else{
//文件不存在
console.log('404,文件找不到');
response.writeHead(404);
}
});
});
fileserver.listen(8080);
console.log('server is running');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  node.js http模块