首页 > 代码库 > nodejs渲染模板

nodejs渲染模板

  1. 为什么要用nodejs来渲染?

   之前前端的任务就是用HTML+CSS 来高保真的还原UI所设计原图,偶尔会使用少量的jq来对页面添加一些特效,页面还要交付给后端开发人员进行数据填充(php jsp)等模板语言,前后端依赖严重,几乎出现任何问题是只有前后端配合才能解决,后来的前后端分离,也就是前后端只用json来交流,前端通过使用ajax来进行数据填充,但是ajax的使用不利于SEO优化和首屏渲染,会造成额外的流量开销(主要在移动端)。

    我所设想的是nodejs只负责渲染页面,数据和后台逻辑还是由JAVA后台实现,nodejs使用JAVA提供的数据接口来对页面进行渲染。

     以下是代码部分略丑:

 

      

var express = require(‘express‘);
var router = express.Router();
var http = require(‘http‘);
// var getdata = http://www.mamicode.com/require(‘../http‘);>//主页
router.get(‘/‘, function(req, res, next) {
//创建请求 var xml = http.request({ host:"localhost", port:3000, method:"GET", path:"/data/", agent:false, header:{ ‘Content-Type‘: ‘application/json‘ } },function (resouce) { resouce.setEncoding(‘utf-8‘); resouce.on(‘data‘,function (progress) { //此处是对接受的数据进行处理 res.render(‘index‘,JSON.parse(progress) ); }); resouce.on(‘end‘,function (data) {      }); xml.on(‘error‘,function (err) { console.log(‘-----error------‘,err); }) }); xml.end(); //告诉服务器此次请求结束 });
//模拟JAVA接口 router.get(‘/data‘,function (req, res, next) { res.send({ "id":"单号", "status":"流转单状态", "data":"审批通过日期", "business_data":"业务日期", "company":"委托单位", "bussiness_company":"业务分公司", "bus_person":"业务员", "provide_person":"运价提供人", "handle_person":"操作分公司", "handle_cus":"操作方客服", "search":"查询", "num":"序号", "bus_id":"业务流转单号", "work_num":"工作号", "odd_id":"流转单类型", "pass_date":"审批通过日期", "company_client":"委托单位", "bus_class":"业务类型", "haulier":"承运人" }); }); module.exports = router;

  app.js

var express = require(‘express‘);
var path = require(‘path‘);
var favicon = require(‘serve-favicon‘);
var logger = require(‘morgan‘);
var cookieParser = require(‘cookie-parser‘);
var bodyParser = require(‘body-parser‘);

var index = require(‘./routes/index‘);
var users = require(‘./routes/users‘);
var exphbs  = require(‘express-handlebars‘);
var app = express();

// view engine setup
app.set(‘views‘, path.join(__dirname, ‘views‘));
//设置模板引擎 app.engine(
‘hbs‘, exphbs({ layoutsDir: ‘views‘, defaultLayout: ‘layout‘, extname: ‘.hbs‘ })); app.set(‘view engine‘, ‘hbs‘); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, ‘public‘, ‘favicon.ico‘))); app.use(logger(‘dev‘)); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(‘public‘)); app.use(‘/‘, index); app.use(‘/users‘, users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error(‘Not Found‘); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get(‘env‘) === ‘development‘ ? err : {}; // render the error page res.status(err.status || 500); res.render(‘error‘); }); module.exports = app;

 

nodejs渲染模板