node模块之 —— http

HTTP服务器

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

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

Node.js实现一个HTTP服务器程序http.js

'use strict';

var http = require('http');
//创建http server
var server = http.createServer(function(request,response){
    //获取http请求的method和URL
    console.log(request.method + ':' + request.url);
    //将http响应200写入response,同时设置Content-Type:'text/html'
    response.writeHead(200,{'Content-Type':'text/html'});
    //将http响应的HTML内容写入response
    response.end('<h1>nodeJS http module</h1>')
})
//让服务器监听8888端口
server.listen(8888);

执行下列命令行

$ node http.js
GET:/
GET:/favicon.ico

在浏览器输入 localhost:8888
node服务器

文件服务器

'use strict';

var fs = require('fs');
var url = require('url');//解析URL
var path = require('path');//处理本地目录使用
var http = require('http');

//从命令行参数获取root目录,默认是当前目录
var root = path.resolve(process.argv[2]||'.');
console.log('根目录路径' + root);

//创建服务器
var server = http.createServer(function(request, response){
    //获取URL的path
    var pathName = url.parse(request.url).pathname;
    console.log('pathname:' + pathName);
    //获取对应的本地文件路径
    var filePath = path.join(root,pathName);
    console.log('filePath:' + filePath);

    //获取文件的状态
    fs.stat(filePath,function(err,stats){
        if(!err && stats.isFile()){
            console.log('200' + request.url);
            //发送200响应
            response.writeHead(200,{'Content-Type':'text/html'});
            response.end('<h1>200</h1>');
            //将文件导向response
            fs.createReadStream(filePath).pipe(response);
        }else{
            //出错了
            console.log('404' + request.url);
            //发送404响应
            response.writeHead(404);
            response.end('404 not found');
        }
    })
});

server.listen(8087);

在浏览器URL里面输入http://localhost:8087/index.html,显示结果如下:
在这里插入图片描述

参考文章:
nodejs
liaoxuefeng

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值