搭建简易服务器 Posted on 2018-08-29 | Words count in article: 241 Node.js简易服务器 一个简单的静态服务器123456789101112131415var 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' ) 支持静态文件动态路由的服务器12345678910111213141516171819202122232425262728var 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)