express使用教程

1、res.end   res.send  res.json

如果服务端没有数据传回客户端,用res.end返回

如果有数据可以使用res.send或者res.json


2、express路由

express路由

例1:

app.get(
  "/index",
  function(req, res, next) {
    console.log(1);
    next();
  },
  function(req, res, next) {
    console.log(2); 
    // 如果没有res.send 或 res.json 或 res.end等响应对象(res)的方法向客户端返回响应,
    // 终结请求响应的循环,来自客户端的请求会一直挂起。
    res.send('abc');
  }
);


例2:

app.get(
  "/index",
  function(req, res, next) {  // 回调1
    console.log(1);
    next("route");  // 位置1
  },
  function(req, res, next) {  // 回调2
    console.log(2);
    next(); // 此处可以是next()或者 next("route"),表示执行下一个相同路由 // 位置2
  }
);

app.get(
  "/index",
  function(req, res, next) {
    console.log(3);
    next();
  },
  function(req, res, next) {
    console.log(4);
    res.send("结束");
  }
);

当位置1是next()方法时,会先执行下一个callback,打印1234;

当位置1是next('route')时,会直接跳过下一个callback直接执行下一个相同的路由,打印134。如果回调2后面还跟着回调3...,当位置1是next('route')时,回调3...都不会再执行。

例3:

app.get(
  "/index",
  function(req, res, next) {
    console.log(1);
    next();
  },
  function(req, res, next) {
    console.log(2);
    var desc = http.STATUS_CODES['500'];
    res.end(desc);  // 200 -> 'ok'  404 -> 'Not Found'  500 -> 'Internal Server Error'
  }
);

例4:

500.js

'use strict';

var http = require('http');

module.exports = function(template) {
    if(!res.statusCode || res.statusCode == 200) {
        res.statusCode = 500;
    }
    var desc = http.STATUS_CODES[res.statusCode];
    res.end(desc + '\n' + err);
    // next(err);后面不再设置error handler, 不能调用next, 否则会触发expressfinalhandler
};


例5:

404.js

'use strict';

module.exports = function(template) {
    return function fileNotFound(req, res, next) {
        var model = {url: req.url, statusCode: 404};
        if(req.xhr) {
            res.send(404, model);
        } else {
            res.status(404);
            res.render(template, res.data);
        }
    }
};


express的使用

express应用生成器

sudo npm install express -g

sudo npm install express-generator -g

在新建项目里执行 express,生成项目工程文件


sudo npm install

执行 npm start

localhost:3000 打开网页




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值