Route
- 从网络请求的URL中得到不同的参数、数据,并根据此来决定使用某些模块的功能,在一个完整的网络应用系统中显得尤为重要;
- Node.js 提供了
url/queryString
两个模块来帮助我们完成这些事情;
const Router = {
route (pathname) {
console.log('the request path name is : ' + pathname)
if (pathname === '/a') {
return 'The world is running with apple'
} else if (pathname === '/b') {
return 'The world is running with banana'
} else {
return 'The world is running with nothing'
}
}
}
module.exports = Router
const http = require('http')
const url = require('url')
function start (route) {
http.createServer((req, rep) => {
const pathname = url.parse(req.url).pathname
console.log('we get the request url pathname: ' + pathname)
const content = route(pathname)
rep.writeHead(200, {'Content-Type': 'text/plain'})
rep.write(content)
rep.end()
}).listen(8888)
console.log('server start')
}
const server = {
start
}
module.exports = server
const server = require('./server')
const router = require('./router')
server.start(router.route)
执行
- 浏览器执行: 127.0.0.0:8888/a
- 浏览器执行: 127.0.0.0:8888/b
- 浏览器执行: 127.0.0.0:8888/c