留言板案例

    代码结构:

    1. public
    2. |-js
    3. |-main.js
    4. |-css
    5. |-main.css
    6. view
    7. |-index.html
    8. |-port.html
    9. main.js
    1. // main.js
    2. var http = require('http')
    3. var fs = require('fs')
    4. var url = require('url')
    5. http.createServer(function(req, res) {
    6. // 获取请求路径
    7. var urlObj = url.parse(req.url, true)
    8. var pathname = urlObj.pathname
    9. if (pathname === '/' || pathname === '/index') { // 获取首页
    10. fs.readFile('./views/index.html', function(err, data) {
    11. if (err) {
    12. res.end('index.html is not found...')
    13. }
    14. res.end(data)
    15. })
    16. } else if (pathname === '/port') { // 跳转port.html
    17. fs.readFile('./views/port.html', function (err, data) {
    18. if(err) {
    19. res.end('port.html is not found...')
    20. }
    21. res.end(data)
    22. })
    23. } else if (pathname === '/pinglun') { // 提交评论,并重定向至 首页
    24. res.statusCode = 302
    25. res.setHeader('Location', '/')
    26. res.end();
    27. } else if (pathname.indexOf('/public/') === 0) { // 可以访问所有静态资源,都在public文件夹下
    28. fs.readFile('.'+pathname, function (err, data) {
    29. if (err) {
    30. res.end('resourse is not found...')
    31. }
    32. res.end(data)
    33. })
    34. } else { // 处理其他请求
    35. res.end(pathname + 'not found...')
    36. }
    37. }).listen(3000, function() {
    38. console.log('server is running on port 3000...')
    39. })