使用ejs模板引擎

let express = require('express');
let fs = require('fs');
let ejs = require('ejs');
let app = express();
let http  = require('http');

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
app.get('/',(req,res)=>{
        ejs.renderFile('./go/服务器展示的页面.html',{name:'baiyang',html:'<li>666</li>'},(err,html)=>{
            console.log(html) //第二位参数必须传json数据;
            res.set('Content-Type', 'text/html');//默认不是html 所有要设置一下,在不同环境下运行会有不同的结果。
            res.send(html);
            // res.status(404).send('请求失败');
            // res.status(404).sendFile(('/absolute/path/to/404.png'));
            // fs模块读取文件的相对路径是以启动server.js的位置为基准的,而不是以server.js文件的位置。 
        });
});
app.listen(3000,()=>{
    console.log('ok')
});

使用ejs模板引擎处理了ajax请求 在安全性相对提高 屏蔽了在展示页面的ajax请求,让数据在后台交互完成,直接渲染在页面上。完全实现了前后端的分离。

猜你喜欢

转载自www.cnblogs.com/l8l8/p/9097480.html