用express搭建网站

先建个简朴的服务器

  • 固然你先得装置express npm install express

//运用express,假如这里的代码复制后运转不了请移步我的github下载源码,随手star给我个小星星勉励哈
//http://github.com/sally2015/express-project
// npm install  运转node main 后接见loaclhost:3000
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);

app.get('/',function(req, res){
    res.send('home');
    
});
app.use('/about',function(req, res){
    res.send('about');
    
});
app.use(function(req, res){


    res.send('404');
    
});

app.use(function(req, res, next){

    res.send('500');
});

app.listen(app.get('port'), function () {
    console.log('Express started on http:localhost'+app.get('port'));
});

  • app.use(function(req,res,next){})默许婚配的路由是‘/’,多个use要运用next()要领,然则运用了,res.end()或许res.send()就不能运用next抵达下一个use了

  • app.get()是增加路由的要领,疏忽大小写,反斜杠,举行婚配时不斟酌查询字符串

//不运用express你可能要这么写
/*
* var http = require('http');
* var server =  http.createServer(function(req, res){
*    if(req.url === '/'){
        res.setHeader('Content-type','text-plain');
        res.write('……');&&res.end();
*   }
*}).listen(3000,'localhost');
*/
  • 对定制的404页面和500页面的处置惩罚与对一般页面的处置惩罚有所区别,用的不是app.get,而是app.use。app.use是express增加中间件的一种要领

  • express中路由和中间件的增加递次至关重要,假如把404处置惩罚器放在一切的路由上面,一般页面的路由就不能用了

  • express能依据回调函数中的参数辨别404和500处置惩罚器

运用handlebars

  • (defaultLayout:’main’)意味着除非你迥殊指明不然一切的视图都是这个规划

var handlebars = require('express3-handlebars') //如今已重命名为express-handlebar了,由于牵一发可能要动满身,我这里就不改了
.create({ 
    defaultLayout: 'main', // 设置默许规划为
});

app.engine('handlebars', handlebars.engine); // 将express模板引擎设置成handlebars 
app.set('view engine', 'handlebars');
  • 建立一个views/layouts/main.handlebars文件

<html lang=”en”>
<head>

<meta charset="UTF-8">
<title>Document</title>

</head>
<body>

{{{body}}}

</body>
<html>

- {{{body}}}注重这里是三个大括号,这个表达式会被每一个视图本身的html庖代
- 离别建立首页、关于、404、500页面,后缀名都是handlebars
  - ```html
views/home.handlebars
=> <h1>welcome to home</h1>
views/about.handlebars
 =><h1>welcome to about</h1>
views/404.handlebars
 =><h1>not found - 404</h1>
views/500.handlebars
 =><h1>500 server error</h1>

视图和静态文件

  • express靠中间件处置惩罚静态文件和视图,中间件是一种模块化手腕,使要求处置惩罚越发轻易

  • static中间件能够将一个或多个目次指派为包括静态资本的目次,个中的资本不经由特别处置惩罚直接发送到客户端

app.use(express.static(__dirname+'/public'));
//如今一切文件都能够相对public直接举行接见,比方public下面有一个img文
//件夹,那末在handlebars中(不须要理会在handlebars的目次构造)直接接见
//途径/img/logo.png
  • 视图和静态资本的区别是它不一定是静态的,html能够动态构建

  • 在项面前目今建一个public的子目次,应当把static中间件加载一切路由之前

向handlebars里通报参数

var args = 'its a arguments';//假造一个参数
//修正此时的about路由
app.get('/about', function(req,res){
    
    res.render('about', {args:args});
});
  • 修正about文件

《用express搭建网站》

  • 此时接见就会获得下面的效果

《用express搭建网站》

以上代码在https://github.com/sally2015/… ch1
———————————————分割线———————————————-

ch2讲讲怎样疾速、可保护的开辟

运用自定义模块

  • ch1为了通报参数在main.js内里定义了一个假造数据,为了将数据分离出来,在根目次下定义一个lib目次,安排一个数据模块m_data.js

var args = 'its a arguments';//假造一个参数

exports.getData = function(){
    return args;
}
  • main.js

var m_data = require('./lib/m_data.js');
app.get('/about', function(req,res){
    
    res.render('about', {args:m_data.getData()});
});

运用nodemon自动重启服务器

  • 每次修正main文件都要ctrl+c住手再运转很累,运用nodeman每次修正都邑帮我们重启服务器

  • 运用也异常简朴,npm install nodemon -g,运转nodemon main

页面测试

  • 须要一个测试框架Mocha —- npm install mocha –save-dev 这里dev的意义是只在开辟时依靠

  • mocha是要运转在客户端的所以把mocha资本放在public目次下

    • public/vendor

    • => node_modules/mocha/mocha.js

    • => node_modules/mocha/mocha.css

  • 测试一般须要一个assert函数

    • npm install chai –save-dev

    • node_modules/chai/chai.js => public/vendor

  • 不让测试一向运转

    • 由于拖慢网站的速率,用户也不须要看到测试效果

    • 希冀的状况是在url背面加上?test=1才加载测试页面

  • 定义中间件来检测查询字符串中的test=1,放在一切路由之前

  • 假如test=1出如今任何页面的字符串查询中,属性res.locals.showTests就会被设为true

  • res.locals对象是要传给视图上下文的一部分

app.use(function(req, res, next){
    res.locals.showTests = app.get('env') !== 'production' 
          && req.query.test === '1';
    next();
});

引入测试框架

  • 修正main.handlebars(今后简写main),修正head

<head>
    <title>Meadowlark Travel</title>
    {{#if showTests}}
        <link rel="stylesheet" href="/vendor/mocha.css">
    {{/if}}
    <script src='//code.jquery.com/jquery-2.0.2.min.js'></script>
</head>
  • 这里在head引入jquery是为了轻易测试

  • 在</body>之前引入mocha和chai,还需引入一个qa/global-test.js剧本

{{#if showTests}}
        <div id="mocha"></div>
        <script src='/vendor/mocha.js'></script>
        <script src='/vendor/chai.js'></script>
        <script>
            mocha.ui('tdd');
            var assert = chai.assert;
        </script>
        <script src='/qa/tests-global.js'></script>
        {{#if pageTestScript}}
            <script src='{{pageTestScript}}'></script>
        {{/if}}
          <script>mocha.run()</script>
    {{/if}}
  • 建立public/qa/tests-global.js全局测试剧本

suite('Global Tests', function(){
    test('page has a valid title', function(){
        assert(document.title && document.title.match(/\S/) && 
          document.title.toUpperCase() !== 'TODO');
    });
});
  • 接见localhost:3000没有任何变化,然则接见localhost:3000?test=1,你会发明加载了测试的文件帮你做的这些东西

《用express搭建网站》

  • 针对about页面举行测试

    • 这里假定测试确保有总有一个指向联络我们页面的链接,建立一个public/qa/tests-about.js

suite('"About" Page Tests', function(){
  test('page should contain link to contact page', function(){
      assert($('a[href="/contact"]').length);
  });
});
  • 在main.js上转变路由/about的参数

    app.get('/about', function(req,res){
      
      res.render('about', {
          args:m_data.getData(),
          pageTestScript:'/qa/tests-about.js'
      });
    });
  • 如今革新页面about会有一个毛病的断言

《用express搭建网站》

  • 只需about模板中有一个链接,这个毛病测试断言就会消逝

  • 比方contact us

《用express搭建网站》

运用部分组件

  • 场景定义一个天色组件,在任何页面都能够挪用,如许的须要反复挪用的能够用部分文件完成

    • 新建一个views/partials/weather.handlebard

<div class="weatherWeight">
    {{#each weather.locations}}
        <div class="location">
            <h3>{{name}}</h3>
            <a href="{{forecastUrl}}">
                {{weather}},{{temp}}
            </a>
        </div>
    {{/each}}
</div>
  • 在weatherData.js中放入假造数据

function getWeatherData(){

    return {
        locations:[
            {
                name:'广州',
                forecastUrl:'https://github.com/sally2015',
                weather:'广州的温度状况',
                temp:'温度'
            },
            {
                name:'深圳',
                forecastUrl:'https://github.com/sally2015',
                weather:'深圳的温度状况',
                temp:'温度'
            },
            {
                name:'珠海',
                forecastUrl:'https://github.com/sally2015',
                weather:'珠海的温度状况',
                temp:'温度'
            }
        ]
    }
}
exports.getWeatherData = getWeatherData
  • 建立一个中间件给res.locals.weather增加数据


//给res.locals.weather增加数据
app.use(function(req, res, next){
    if(!res.locals.weather){
        res.locals.weather = {};

    }
    res.locals.weather = m_weatherData.getWeatherData();
    next();
});

  • 将组件放在主页home上

<h1>welcome to home</h1>
{{>weather}}
  • 语法{> partialname}能够让你在视图中包括一个部分文件,express-handlebars会在views/partials寻觅

  • 你能够将这个语法放在任何你须要的页面上

《用express搭建网站》

客户端运用模板和动态猎取数据

  • 客户端运用handlebars须要加载handlebars文件,你能够从node_moudles内里找,像一般文件一样引入即可

  • 定义一个view/partials/ajaxtest.handlebars文件

<script id='ajaxtest' type='text/x-handlebars-template'>
    Marry hadd a little <b>\{{animal}}</b>
    its<b>\{{bodyPart}}</b>
    was <b>\{{adjective}}</b>as <b>\{{noun}}</b>
</script>
<button id='btn'>动态猎取数据<tton>
<div id="content">
    
</div>
<script>
    $(document).ready(function(){
        var template = Handlebars.compile($('#ajaxtest').html());
        
        $('#btn').click(function(){
            $.ajax('/data/ajaxtest',{
                success:function(data){
                    $('#content').html(template(data));
                }
            });
        });
    });
    
</script>
  • 在main.js中设定接口

app.get('/data/ajaxtest', function(req, res) {
    res.json({
            animal:'dog',
            bodyPart:'tail',
            adjective : 'sharp',
            noun : 'run'
        });
});
  • 在你想要的视图内里到场{{>ajaxtest}}

  • 这时候当你点击按钮就会要求到数据,注重接口运用的要领是json

《用express搭建网站》
——————–分割线————————————ch2 https://github.com/sally2015/…

    原文作者:Obeing
    原文地址: https://segmentfault.com/a/1190000007124164
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞