express

889 阅读1分钟

只看文档是没有效果的,只有在实践中试错才能真正理解书中的文字。

安装

  1. 创建文件夹 express
  2. 初始化 package.json 文件 (enter 默认回车)
npm init
  1. 安装express 依赖并保存在列表中
npm install --save express

Hello World

代码片段


    const express = require('express')
    const app = express()
    app.get('/', function(req, res){
        res.send('hello world')
    })
    
    const server = app.listen('3001', 'localhost', function(){
        const host = server.address().address
        const port = server.address().port
        console.log('Example app is listening at http://%s:%s', host, port)
    })
    
    // Example app is listening at http://127.0.0.1:30001

express 渲染页面

  • 目前 项目目录


    const html = __dirname + '/index.html'
    // 加入html 引擎
    app.engine('html', require('ejs').__express);
    
    app.set('view engine', 'html');
    app.get('/',function (req, res){
      res.render(html)
    })

遇到问题:

  1. 渲染html 时 没有使用app.engine ,添加html 引擎

解决方法:

    app.engine('html', require('ejs').__express);

⚠️ 另: 设置渲染html 文件时可以省略html扩展名

    app.set('view engine', 'html'); 

  1. 没有加载静态资源

利用 Express 托管静态文件

  • express.static 中间件
    app.use(express.static(path.join(__dirname, 'public')))
    // public存放静态文件的文件夹

  • 如果你希望所有通过 express.static 访问的文件都存放在一个“虚拟(virtual)”目录(即目录根本不存在)下面,可以通过为静态资源目录指定一个挂载路径的方式来实现,如下所示:
    app.use('/static', express.static('public'));
  • 现在,你就爱可以通过带有 “/static” 前缀的地址来访问 public 目录下面的文件了
    http://localhost:3000/static/images/kitten.jpg
    http://localhost:3000/static/css/style.css
    http://localhost:3000/static/js/app.js
    http://localhost:3000/static/images/bg.png
    http://localhost:3000/static/hello.html

哈哈哈结合之前的React和webpack ~ em... 终于有页面了~

✌️

ps: 由于node中渲染的页面刚好在我加载的静态资源内, 所以不使用html引擎, view/index.html也可以访问