node.js搭建静态服务器
2018-04-07 本文已影响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 数据
- 使用 http://easy-mock.com/
- 使用 http://rapapi.org/org/index.do
-
使用 server-mock
5.png
写一个服务器
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
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。