zoukankan      html  css  js  c++  java
  • node.js中express框架的基本使用

    express是一个基于node.js平台的,快速,开放,极简的web开发框架。

    一、安装 express

    npm install express --save
    

      

    二、简单使用 express

    //引入express
    const express = require('express');
    //创建一个应用
    let app = express();
    
    //匹配GET请求路径设置回调函数
    app.get('/hello', function (req, res) {
        res.end('hello');
    });
    
    //监听端口
    app.listen(8888, function () {
        console.log('port : 8888');
    });
    

    通过访问 localhost:8888/hello 我们就可以看到内容输出了。

    当然 express 还支持其他的一些请求方法,比如 app.post(),app.put(),app.delete(),app.head() 等。

    //引入express
    const express = require('express');
    //创建一个应用
    let app = express();
    
    //匹配POST请求
    app.post('/hello', function (req, res) {
        res.end('post hello');
    });
    
    //监听端口
    app.listen(8888, function () {
        console.log('port : 8888');
    });

    如果我们想要匹配所有的请求路径,可以使用通配符 * 号。

    //引入express
    const express = require('express');
    //创建一个应用
    let app = express();
    
    app.get('/hello', function (req, res) {
        res.end('hello');
    });
    
    //*号匹配所有路径
    app.get('*', function (req, res) {
        res.end('not found');
    });
    
    //监听端口
    app.listen(8888, function () {
        console.log('port : 8888');
    });
    

    express 还提供了 all() 方法,可以匹配所有请求方法。

    //引入express
    const express = require('express');
    //创建一个应用
    let app = express();
    
    //匹配所有请求方法
    app.all('/hello', function (req, res) {
        res.end('all hello');
    });
    
    //监听端口
    app.listen(8888, function () {
        console.log('port : 8888');
    });
    

      

    三、express 中间件的概念

    express中间件就是处理http请求的函数,用来完成一些特定的操作,比如登陆检查,权限控制等等。

    1、一个中间件处理完请求和响应,可以把数据传递给下一个中间件。

    2、在回调函数中使用 next(),就可以让请求继续向下传递。

    3、通过不同路径,分别执行不同的中间件。

    我们可以使用 use() ,在路由数组中添加一个中间件。注意我们设置的路由路径最终会存放在一个数组里,由上到下的把路径加入这个数组中。 

    //引入express
    const express = require('express');
    //创建一个应用
    let app = express();
    
    //如果没有设置路径,则会匹配全部
    app.use(function (req, res, next) {
        console.log('匹配全部路径');
        //注意这里如果不调用next(),则请求并不会向下传递。
        next();
    });
    
    app.use('/hello', function (req, res, next) {
        console.log('use hello');
        next();
    });
    
    app.get('/hello', function (req, res, next) {
        console.log('get hello');
        next();
    });
    
    //监听端口
    app.listen(8888, function () {
        console.log('port : 8888');
    });
    

    next() 函数可以传入一个参数,表示错误信息,默认将执行错误中间件。

    //引入express
    const express = require('express');
    //创建一个应用
    let app = express();
    
    app.get('/hello', function (req, res, next) {
        console.log('get hello');
        next('error!!!');
    });
    
    //注意错误处理中间件的参数是4个
    app.use(function (err, req, res, next) {
        console.log(err);
        res.end(err);
    });
    
    //监听端口
    app.listen(8888, function () {
        console.log('port : 8888');
    });
    

      

    四、express中的request对象

    在express中对原生的req请求对象进行了扩展,添加了一些属性和方法。

    //引入express
    const express = require('express');
    //创建一个应用
    let app = express();
    
    app.get('/hello', function (req, res, next) {
        //主机名
        res.write('req.hostname : ' + req.hostname + '
    ');
        //请求URL的路径
        res.write('req.path : ' + req.path + '
    ');
        //查询字符串对象
        res.write('req.query : ' + JSON.stringify(req.query) + '
    ');
        //请求的远程IP地址
        res.write('req.ip : ' + req.ip + '
    ');
        //请求方法
        res.write('req.method : ' + req.method + '
    ');
        res.end();
    });
    
    //监听端口
    app.listen(8888, function () {
        console.log('port : 8888');
    });
    

    通过 req.params 获取路径里的参数

    //引入express
    const express = require('express');
    //创建一个应用
    let app = express();
    
    app.get('/list/:key/:page/:size', function (req, res, next) {
        //注意,设置了多少参数,地址就需要传入多少参数
        res.end(JSON.stringify(req.params));
    });
    
    //监听端口
    app.listen(8888, function () {
        console.log('port : 8888');
    });
    

      

    五、express中的response对象

    express中也对原生的res对象进行了扩展,添加了一些属性和方法。

    const path = require('path');
    //引入express
    const express = require('express');
    //创建一个应用
    let app = express();
    
    app.get('/send/str', function (req, res, next) {
        //send方法会自动判断数据类型,并进行相应的head信息设置
        //如果参数是字符串,则Content-Type为 text/html
        res.send('hello, world');
    });
    
    app.get('/send/arr', function (req, res, next) {
        //如果参数是一个数组,则返回json
        res.send([1, 2, 3]);
    });
    
    app.get('/send/obj', function (req, res, next) {
        //如果参数是一个对象,则返回json
        res.send({name: 'xiaoxu', age: 24});
    });
    
    app.get('/send/number', function (req, res, next) {
        //如果是一个数字,则返回相应状态码短语
        res.send(404);
    });
    
    app.get('/download', function (req, res, next) {
        //提示下载文件
        res.download('./1.txt');
    });
    
    app.get('/json', function (req, res, next) {
        //响应json对象
        res.json({name: 'xiaoxu'});
    });
    
    app.get('/jsonp', function (req, res, next) {
        //客户端请求时,需要带上callback=test
        res.jsonp('hello');
    });
    
    app.get('/redirect', function (req, res, next) {
        //重定向到一个地址
        res.redirect('http://www.baidu.com');
    });
    
    app.get('/sendfile', function (req, res, next) {
        //发送一个文件
        res.sendFile(path.resolve('./1.txt'));
    });
    
    app.get('/sendstatus', function (req, res, next) {
        //发送一个状态码
        res.sendStatus(302);
    });
    
    //监听端口
    app.listen(8888, function () {
        console.log('port : 8888');
    });
    

      

    六、ejs模板的使用

    支持express的模板有很多种,这里我们使用ejs作为模板引擎。

    安装ejs:

    npm install ejs
    

    使用ejs模板

    const path = require('path');
    const express = require('express');
    //创建一个应用
    let app = express();
    //设置模板引擎
    app.set('view engine', 'ejs');
    //设置模板目录
    app.set('views', path.join(__dirname, 'views'));
    //监听
    app.listen(8888);
    

    如果我们希望,ejs能够渲染html页面,可以使用如下

    const path = require('path');
    const express = require('express');
    let app = express();
    
    //设置视图引擎为html引擎
    app.set('view engine', 'html');
    //设置视图的路径
    app.set('views', path.join(__dirname, 'views'));
    //配置html引擎
    app.engine('html', require('ejs').__express);
    
    app.listen(8888);
    

    渲染视图,输出内容。

    const path = require('path');
    const express = require('express');
    let app = express();
    
    app.set('view engine', 'html');
    app.set('views', path.join(__dirname, 'views'));
    app.engine('html', require('ejs').__express);
    
    app.get('/hello', function (req, res, next) {
        //参数一表示模板的名称,会在当前项目目录下的views目录查找
        //参数二表示传入模板中的数据
        res.render('hello', {
            name: 'xiaoxu',
            age: 24
        });
    });
    
    app.listen(8888);
    

    hello.html的代码:

    <!doctype html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <%= name %>
        <%= age %>
    </body>
    </html>
    

      

    七、静态文件服务器

    有些时候我们需要在页面上加载css,js,img等静态资源,指定存放静态资源的目录,浏览器发出非html文件请求时,服务器会到这个目录下找对应的资源。

    const path = require('path');
    const express = require('express');
    let app = express();
    
    app.set('view engine', 'html');
    app.set('views', path.join(__dirname, 'views'));
    app.engine('html', require('ejs').__express);
    
    //注意express.static这个中间件是express内置的
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.get('/hello', function (req, res, next) {
        //参数一表示模板的名称,会在当前项目目录下的views目录查找
        //参数二表示传入模板中的数据
        res.render('hello', {
            name: 'xiaoxu',
            age: 24
        });
    });
    
    app.listen(8888);
    

      

    八、使用body-parser中间件解析post过来的数据

    安装body-parser

    npm install body-parser
    

    使用body-parser

    const path = require('path');
    const express = require('express');
    const bodyParser = require('body-parser');
    let app = express();
    
    app.set('view engine', 'html');
    app.set('views', path.join(__dirname, 'views'));
    app.engine('html', require('ejs').__express);
    
    //解析 application/json
    app.use(bodyParser.json());
    //解析 application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({extended:false}));
    
    app.post('/form', function (req, res) {
        console.log(req.body);
    });
    
    app.listen(8888);
    

      

  • 相关阅读:
    PythonStudy——greenlet 协程
    PythonStudy——事件 Event
    PythonStudy——单线程并发的实现
    2015年的总结
    kylin一种OLAP的实现
    分布式消息队列的使用kakfa
    第一次听到了docker
    Hive分布式的数据仓库
    dubbo服务框架学习
    Storm实时计算框架的编程模式
  • 原文地址:https://www.cnblogs.com/jkko123/p/10279972.html
Copyright © 2011-2022 走看看