express框架初步

  • express框架初步使用
var exp = require('express');
var ejs = require('ejs');
var app = new exp();
app.set("view engine","ejs");
app.get('/index',function (req,res) {
    res.render('tianwadi',{});
});//默認狀況下,express使用views目錄下的.ejs文件

app.listen(8888,'127.0.0.1');
  • express設置模板目錄和模板引擎
var exp = require('express');
var ejs = require('ejs');
var app = new exp();
app.engine('html',ejs.__express);//註冊引擎類型默認爲ejs
app.set('view engine','html');//設定引擎類型
app.set('views',__dirname+"/tpl");//自定義模板存放目錄
app.get('/index',function (req,res) {
    res.render('index',{});
});

app.listen(8888,'127.0.0.1');
  • 對靜態文件的解析和引入
var exp = require('express');
var ejs = require('ejs');
var app = new exp();
app.use(exp.static('static'));//指定靜態文件根目錄---app.use也是中間件的用法
app.engine('html',ejs.__express);//註冊引擎類型默認爲ejs
app.set('view engine','html');//設定引擎類型
app.set('views',__dirname+"/tpl");//自定義模板存放目錄
app.get('/index',function (req,res) {
    res.render('index',{"headtitle":'ejs首頁'});
});

app.listen(8888,'127.0.0.1');

html部分html

......省略部分
<footer class="footer mt-auto py-3">
    <div class="container">
        <span class="text-muted">Place sticky footer content here.</span>
    </div>
</footer>
<script src="/js/jquery-3.4.1.min.js"></script></body>
</html>
  • 項目目錄

 

  •  靜態服務託管(感受像是給真實的靜態文件夾起了個‘別名’,url中用別名加上下級文件夾能夠訪問到資源)
var exp = require('express');
var ejs = require('ejs');
var app = new exp();
app.use(exp.static('static'));//指定靜態文件根目錄
app.use('/multimedia',exp.static('static'));//給真實的項目文件夾static起了個別名multimedia
app.engine('html',ejs.__express);//註冊引擎類型默認爲ejs
app.set('view engine','html');//設定引擎類型
app.set('views',__dirname+"/tpl");//自定義模板存放目錄
app.get('/index',function (req,res) {
    res.render('index',{"headtitle":'ejs首頁'});
});

app.listen(8888,'127.0.0.1');

html部分jquery

......
<div class="container">
        <h1 class="mt-5"><%=headtitle%></h1>
        <p class="lead">Pin a footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS. A fixed navbar has been added with <code>padding-top: 60px;</code> on the <code>main &gt; .container</code>.</p>
        <p><img src="/multimedia/pic/EEhTIVVVUAAiht3.jpg" width="400"></p>
        <p>Back to <a href="/docs/4.3/examples/sticky-footer/">the default sticky footer</a> minus the navbar.</p>
    </div>
......

相關文章
相關標籤/搜索