zoukankan      html  css  js  c++  java
  • 【Express】路由

    var express = require('express');
    
    var app = express();
    app.set('port', process.env.PORT || 3000);
    
    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和500页面的处理与对普通页面的处理应有所区别:用的不是app.get,而是app.use。
    app.use是Express添加中间件的一种方法。
    在Express中,路由和中间件的添加顺序至关重要。
    如果我们把404处理器放在所有路由上面,那首页和关于页面就不能用了,访问这些URL得到的都是404。
     */
    
    // Express能根据回调函数中参数的个数区分404和500处理器
    // 定制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.' );
    });

    中间件

    var app = require('express')();
    
    app.use(function(req, res, next){
        console.log('
    
    ALLWAYS');
        next();
    });
    
    app.get('/a', function(req, res){
        console.log('/a: 路由终止');
        res.send('a');
    });
    app.get('/a', function(req, res){
        console.log('/a: 永远不会调用');
    });
    
    app.get('/b', function(req, res, next){
        console.log('/b: 路由未终止');
        next(); 
    });
    app.use(function(req, res, next){
        console.log('SOMETIMES');
        next(); 
    });
    app.get('/b', function(req, res, next){
        console.log('/b (part 2): 抛出错误' );
        throw new Error('b 失败');
    });
    app.use('/b', function(err, req, res, next){
        console.log('/b 检测到错误并传递');
        next(err);
    });
    
    app.get('/c', function(err, req){
        console.log('/c: 抛出错误');
        throw new Error('c 失败');
    });
    app.use('/c', function(err, req, res, next){
        console.log('/c: 检测到错误但不传递');
        next(); 
    });
    
    app.use(function(err, req, res, next){
        console.log('检测到未处理的错误: ' + err.message);
        res.send('500 - 服务器错误');
    });
    
    app.use(function(req, res){
        console.log('未处理的路由');
        res.send('404 - 未找到');
    });
    
    app.listen(3000, function(){
        console.log('监听端口3000');
    });
  • 相关阅读:
    Cocos2d-x 2.x项目创建
    Mac OS 使用Git
    Android Studio And Gradle
    Mac OS环境变量配置(Android Studio之Gradle)
    【Android UI】 Shape详解
    JS-OC通信之Cordova简介
    python类的定义和使用
    Android屏幕适配常识
    Python面试315题
    第十五篇 Python之文件处理
  • 原文地址:https://www.cnblogs.com/jzm17173/p/4260402.html
Copyright © 2011-2022 走看看