美文网首页
Node & Express

Node & Express

作者: 从此以后dapeng | 来源:发表于2016-11-25 17:37 被阅读55次

安装 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'); 
});

相关文章

  • Node & Express

    安装 Node 用Node实现的简单Web服务器 创建一个 hello.js 文件 在和 helloWorld.j...

  • express安装

    express是node的框架,因此express基于node,安装express前必须安装node。 node不...

  • 项目地址

    1. 以express为基础的node.js项目 node-express: 一个基于express写的node项...

  • 2016.08.08

    plan axure/node/express/ 工作/算法工作 axure 算法 express node 健身...

  • node express 微信开发

    wechat-node 微信开发 基于node express框架 介绍 node express 微信开发 获取...

  • Node.js学习express框架

    Node.js框架学习 express.js express.js是什么 Express基于Node.js平台,快...

  • node.js学习笔记(3)

    Node.js Express 框架的使用 Express 简介 Express 是一个简洁而灵活的 node.j...

  • Node.js+Express.js+Redis+MySQL=R

    目录 几点杂谈 Node + Express 环境配置略述+开源库的选择 Express.js 框架 Node +...

  • [译] Node & Express 入门指南

    原文地址:Introduction to Node & Express 原文作者:Eric Elliott 译文出...

  • 基于Node.js的Express框架

    一、什么是Express Express基于Node.js封装的,快速、开放、极简的 Node.js Web 开发...

网友评论

      本文标题:Node & Express

      本文链接:https://www.haomeiwen.com/subject/rhqwpttx.html