留言板案例
代码结构:
public
|-js
|-main.js
|-css
|-main.css
view
|-index.html
|-port.html
main.js
// main.js
var http = require('http')
var fs = require('fs')
var url = require('url')
http.createServer(function(req, res) {
// 获取请求路径
var urlObj = url.parse(req.url, true)
var pathname = urlObj.pathname
if (pathname === '/' || pathname === '/index') { // 获取首页
fs.readFile('./views/index.html', function(err, data) {
if (err) {
res.end('index.html is not found...')
}
res.end(data)
})
} else if (pathname === '/port') { // 跳转port.html
fs.readFile('./views/port.html', function (err, data) {
if(err) {
res.end('port.html is not found...')
}
res.end(data)
})
} else if (pathname === '/pinglun') { // 提交评论,并重定向至 首页
res.statusCode = 302
res.setHeader('Location', '/')
res.end();
} else if (pathname.indexOf('/public/') === 0) { // 可以访问所有静态资源,都在public文件夹下
fs.readFile('.'+pathname, function (err, data) {
if (err) {
res.end('resourse is not found...')
}
res.end(data)
})
} else { // 处理其他请求
res.end(pathname + 'not found...')
}
}).listen(3000, function() {
console.log('server is running on port 3000...')
})