node.js搭建静态服务器

作者: 好奇男孩 | 来源:发表于2018-04-07 18:14 被阅读14次

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
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

相关文章

  • XDL_NO.5 Node.js 中的I/O交互

    回顾下上节课的知识点 搭建一个简单的 Node.js 服务器 利用Node.js 搭建一个静态网站 今天的主题是:...

  • Node.js搭建静态服务器

    写在开头,本文是node.js最最初级的搭建静态服务器,比较适合新手入门,大神请绕道哦~ Node.js 是一个基...

  • Node.js搭建本地静态服务器

    Node.js搭建本地静态服务器 了解网络 HTTP(超文本传输协议) 主要内容 请求 响应 连接(三次握手) 断...

  • 初学NODE 学习笔记(二)-常用内置模块

    (二)用node.js内置模块,模拟搭建简单服务器(静态资源文件请求的处理); 明确:NODE是用来开发后台,服务...

  • 私有npm服务器搭建

    私有npm服务器搭建 标签(空格分隔): Node.js 私有npm服务器搭建 本次搭建是在ubuntu环境下搭建...

  • 搭建私有npm服务器教程

    私有npm服务器搭建 标签(空格分隔): Node.js 私有npm服务器搭建 本次搭建是在ubuntu环境下搭建...

  • HEXO 搭建博客

    Hexo搭建Github静态博客 hexo —— 简单、快速、强大的Node.js静态博客框架 主题:https:...

  • 当前文集 node.js 写一个静态资源服务器记录,是为了给自己学习用 node.js 写静态资源服务器做一个记录...

  • CentOS 搭建Http静态服务器环境

    搭建Http静态服务器环境 搭建静态网站,首先需要部署环境。下面的步骤,将告诉大家如何在服务器上通过 Nginx ...

  • node.js搭建静态服务器

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

网友评论

    本文标题:node.js搭建静态服务器

    本文链接:https://www.haomeiwen.com/subject/ciyqhftx.html