Node & Express

2016-11-25  本文已影响55人  从此以后dapeng

安装 Node


用Node实现的简单Web服务器


创建一个 hello.js 文件

var http = require('http'); 
 
http.createServer(function(req,res){ 
        res.writeHead(200, { 'Content-Type': 'text/plain' });  
        res.end('Hello world!'); 
}).listen(3000); 
 
console.log('Server started on localhost:3000');

在和 helloWorld.js 同一个目录下,输入 node hello.js

然后打开浏览器访问 http://localhost:3000

第一个 Web 服务器就建成啦

路由


路由是指处理客户端发出的不同请求路径的机制。

比如:如何处理以下的请求

http://localhost:3000/
http://localhost:3000/about
http://localhost:3000/may-not-exist

给以上的服务器增加路由处理

var http = require('http'); 
 
http.createServer(function(req,res){ 
        // 规范化 url,去掉查询字符串、可选的反斜杠,并把它变成小写 
        var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();  
        switch(path) { 
                case '': 
                        res.writeHead(200, { 'Content-Type': 'text/plain' }); 
                        res.end('Homepage'); 
                        break; 
                case '/about': 
                        res.writeHead(200, { 'Content-Type': 'text/plain' }); 
                        res.end('About'); 
                        break; 
                default: 
                        res.writeHead(404, { 'Content-Type': 'text/plain' });  
                        res.end('Not Found'); 
                        break; 
        } 
}).listen(3000); 
 
console.log('Server started on localhost:3000');

静态资源服务


用 Node 提供静态资源只适用于初期的小型项目,对于比较大的项目,你应该会想用 Nginx 或 CDN 之类的代理服务器来提供静态资源。

Node 处理静态资源文件,必须打开文件,读取其中的内容,然后将这些内容发送给浏览器。

准备工作:
创建一个名为 public 的目录,
在这个目录下创建文件 home.html、about.html、notfound.html,
创建子目录 img,在其中添加一个名为logo.jpg 的图片。
在你的 HTML 文件中这样引用 logo:<img src="/img/logo.jpg" alt="logo">

目录

修改hello.js

var http = require('http'), 
        fs = require('fs'); 
 
function serveStaticFile(res, path, contentType, responseCode) { 
        if(!responseCode) responseCode = 200;  
        fs.readFile(__dirname + path, function(err,data) { 
                if(err) { 
                        res.writeHead(500, { 'Content-Type': 'text/plain' }); 
                        res.end('500 - Internal Error'); 
                } else {  
                        res.writeHead(responseCode,  { 'Content-Type': contentType }); 
                        res.end(data); 
                }  
        }); 
} 

http.createServer(function(req,res){ 
        // 规范化 url,去掉查询字符串、可选的反斜杠,并把它变成小写 
        var path = req.url.replace(/\/?(?:\?.*)?$/, '') .toLowerCase();  
        switch(path) { 
                case '':  
                        serveStaticFile(res, '/public/home.html', 'text/html');  
                        break; 
                case '/about': 
                        serveStaticFile(res, '/public/about.html', 'text/html'); 
                        break; 
                case '/img/logo.jpg': 
                        serveStaticFile(res, '/public/img/logo.jpg', 'image/jpeg');  
                        break; 
                default: 
                        serveStaticFile(res, '/public/404.html', 'text/html', 404);  
                        break; 
        } 
}).listen(3000); 
 
console.log('Server started on localhost:3000');

Express


安装express :npm install --save express

创建 meadowlark.js 文件

var express = require('express'); 
 
var app = express(); 
 
app.set('port', process.env.PORT || 3000); 
 
// 定制 404 页面 
app.use(function(req, res){  
        res.type('text/plain'); 
        res.status(404); 
        res.send('404 - Not Found'); 
}); 
 
// 定制 500 页面 
app.use(function(err, req, res, next){  
        console.error(err.stack); 
        res.type('text/plain'); 
        res.status(500); 
        res.send('500 - Server Error'); 
}); 
 
app.listen(app.get('port'), function(){ 
  console.log( 'Express started on http://localhost:' + 
    app.get('port') + '; press Ctrl-C to terminate.' ); 
});

启动这个服务器 node meadowlark.js ,然后访问 http://localhost:3000

最后, 给首页和关于页面加上路由。在 404 处理器之前加上两个新路由

app.get('/', function(req, res){  
         res.type('text/plain'); 
         res.send('Meadowlark Travel'); 
}); 
app.get('/about', function(req, res){ 
         res.type('text/plain'); 
         res.send('About Meadowlark Travel'); 
}); 
 
// 定制 404 页面 
app.use(function(req, res, next){  
        res.type('text/plain'); 
        res.status(404); 
        res.send('404 - Not Found'); 
});
上一篇 下一篇

猜你喜欢

热点阅读