搭建简易服务器

Node.js简易服务器

一个简单的静态服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var http = require('http')
var fs = require('fs')

var server = http.createServer(function(req, res){
try{
var fileContent = fs.readFileSync(__dirname + '/static' + req.url)
res.write(fileContent)
}catch(e){
res.writeHead(404, 'not found')
}
res.end()
})

server.listen(8080)
console.log('visit http://localhost:8080' )

支持静态文件动态路由的服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var http = require('http')
var fs = require('fs')
var url = require('url') // 引入url模块解析url地址,eg:127.0.0.1:8080/index.html?a=1&b=2 需要将?后的参数去掉

http.createServer(function(req, res){
var pathObj = url.parse(req.url, true)
console.log(pathObj)

switch (pathObj.pathname) { // 路由
case '/getWeather':
var ret
if(pathObj.query.city == 'beijing'){
ret = { city: 'beijing', weather: '晴天' }
}else{
ret = { city: pathObj.query.city, weather: '不知道' }
}
res.end(JSON.stringify(ret))
break;
default:
try{ // 静态服务器
var fileContent = fs.readFileSync(__dirname + '/static' + pathObj.pathnamel)
res.write(fileContent)
}catch(e){
res.writeHead(404, 'not found')
}
res.end( )
}
}).listen(8080)
0%