node.js搭建静态服务器

http-server

使用 http-server node工具启动一个静态服务器
打开终端或者 gitbash,输入

npm install -g http-server

即安装成功(如果提示命令不存在,需要先下载安装 nodejs),安装后切换到对应目录,启动静态服务器,如

cd ~/Desktop/你的文件夹
http-server
3.png

4.png

server-mock

使用 server-mock node工具启动一个能处理静态文件和动态路由的服务器

线上mock 数据

写一个服务器

1.通过http模块创建一个简单的服务器

var http = require("http");
var server = http.createServer(function(request,response){
 setTimeout(function () {
     response.setHeader('Content-Type','text/html;charset=utf-8');
     response.writeHeader(200,"OK");
     response.write('<h1>hello world<h1>');
     response.end();
     //console.log(request)
     //console.log(response);
 },3000);
});
server.listen(3646);
console.log('visit http://localhost:3646');
[图片上传中...(7.png-cac2c3-1523090285076-0)]

7.png

2.通过fs模块读取静态资源,并增加容错处理;

var http = require('http');
var fs = require('fs');
var server = http.createServer(function (req,res) {
    try{
        var fileContent = fs.readFileSync(__dirname+"/static"+req.url);
        console.log(__dirname);
        console.log(req.url);
        res.write(fileContent)
    }catch(e){
        res.writeHead(404,'not found')
    }
    res.end()
});
server.listen(3647);
console.log('visit http://localhost:3647');
8.png

9.png

10.png

3.通过url模块可以解析输入URL,实现路由解析与mock数据功能

var http = require('http');
var fs =require('fs');
var url =require('url');

http.createServer(function (req,res) {
    var pathObj = url.parse(req.url,true);
    console.log(pathObj);
    switch(pathObj.pathname){
        case'/getMusic':
            var ret;
            if(pathObj.query.age=="18"){
                ret = {
                    age:'18',
                    music:'hello world'
                }
            }else{
                ret={
                    age:pathObj.query.age,
                    music:'不知道'
                }
            }
            res.end(JSON.stringify(ret));
            break;
        case'/user/123':
            res.end(fs.readFileSync(__dirname+'/static/user.text'));
            break;
        default :
            res.end(fs.readFileSync(__dirname+'/static'+pathObj.pathname))
    }
}).listen(3649);
console.log("visit http://localhost:3649");
var xhr =new XMLHttpRequest();
xhr.open('GET','/getMusic?age=18',true);
xhr.send();
xhr.onload= function () {
    console.log(JSON.parse(xhr.responseText))
};
12.png
11.png

4.增加面对post请求方式mock数据

var http = require('http');
var path = require('path');
var fs = require('fs');
var url = require('url');

var routes = {
    '/a': function (req, res) {
        res.end(JSON.stringify(req.query))
    },
    '/b': function (req,res) {
        res.end('match /b')
    },
    '/a/c': function (req,res) {
        res.end('match /a/c')
    },

    '/search':function(req,res){
        res.end('username='+req.body.username+',password='+req.body.password)
    }
};
var server = http.createServer(function(req,res){
    routePath(req,res)
});
server.listen(3648);
console.log("visit http://localhost:3648");
function routePath(req,res){
    var pathObj = url.parse(req.url,true);
    var handleFn = routes[pathObj.pathname];
    if(handleFn){
        req.query = pathObj.query;
        var body = '';
        req.on('data',function(chunk){
            body+= chunk;
        }).on('end',function(){
            req.body = parseBody(body);
            handleFn(req,res);
        })
    }else  {
        staticRoot(path.resolve(_dirname,'static'),req,res)
    }
}
function parseBody(body){
    console.log(body);
    var obj = {};
    body.split('&').forEach(function (str) {
        obj[str.split('=')[0]] = str.split('=')[1]
    });
    return obj;
}
function staticRoot(staticPath,req,res){
    var pathObj = url.parse(req.url,true);
    var filePath = path.join(staticPath,pathObj.pathname);
    fs.readFile(filePath,'binary', function (err,content) {
        if(err){
            res.writeHead('404',"Not Found");
            return res.end();
        }
        res.writeHead(200,"OK");
        res.write(content,'binary');
        res.end();
    })
}

作者:彭荣辉
链接:https://www.jianshu.com/u/0f804364a8a8
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,833评论 19 139
  • 写在开头,本文是node.js最最初级的搭建静态服务器,比较适合新手入门,大神请绕道哦~ Node.js 是一个基...
    IrisLong阅读 8,718评论 1 13
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,986评论 25 709
  • 【健心践行打卡第163天:】(2018.3.20) 一、功课: 读功课30分钟,快走5公里,大礼拜108个,完成。...
    Yoyo袁阅读 1,283评论 4 1
  • 现在凌晨三点,我又失眠了,和昨晚一样。旁边的朋友打着呼噜,这不是我失眠的原因。我对我的陪护身份很陌生,有兴奋的...
    丰行者阅读 1,009评论 3 1

友情链接更多精彩内容