zoukankan      html  css  js  c++  java
  • node.js之express框架入门篇

    一、express框架简介

      express框架是后台的Node框架,在后台的受欢迎的程度,和jQuery一样

      英语官网:http://expressjs.com/

      中文官网:http://www.expressjs.com.cn/

    二、安装 express

      1、使用npm命令

            

      会在当前目录生成一个pakage.json的文件,里面会保存依赖

      2、安装experss框架

        

       --save参数,表示自动修改package.json文件,自动添加依赖项。

     三、express的好处

      首先给大家看一下文件的结构

      1、路由能力

      1.js:用express框架实现路由

    var express=require("express");
    var app=express();
    app.get("/",function (req,res) {
        res.send("你好");
    });
    app.get("/haha",function (req,res) {
        res.send("这是haha页面,哈哈哈哈哈");
    
    });
    app.get(/^/student/([d]{10})$/,function (req,res) {
        res.send("学生信息,学号"+req.param[0]);
    
    });
    app.get("/techer/:gonghao",function (req,res) {
        res.send("老师信息,工号",req.params.gonghao);
    
    })
    app.listen(3000);

    路由简单清晰,并且不需要写很多的判断语句

     2、静态文件伺服能力

    2.js:实现静态文件的加载

    var express=require('express');
    var app=express();
    app.use(express.static("./public"));
    app.get("./haha",function (req,res) {
        res.send("haha");
    
    });
    app.listen(3000);

     只需要一行代码,就可以把public的所有文件加载出来;不会像原生node那样麻烦

     3、模板引擎

    haha.ejs

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <h1>哈哈哈</h1>
        <ul>
            <%for(var i=0;i<news.length;i++){%>
                <li><%=news[i]%></li>
            <%}%>
        </ul>
    
    </body>
    </html>

    3.js

    var express=require('express');
    var app=express();
    app.set("view engine","ejs");
    app.get("/",function (req,res) {
        res.render("haha",{
            "news":["aaaa","bbbb","cccc"]
        })
    });

     不需要require ejs模块,app.set("view engine","ejs")可以自动识别ejs文件

    
    
    
  • 相关阅读:
    get和post
    java学习day34-Cookie技术
    java学习day33-Maven-相关
    在Linux设置完共享文件夹后无法显示Windows里的文件
    Tomcat-把tomcat的端口号从8080修改为80
    是否忘记向源中添加“#include“StdAfx.h””
    php-fpm配置文件详解
    Web安全常见漏洞修复建议
    blog个性化设置
    使用 notepad++ 编辑器在行首、行尾添加字符
  • 原文地址:https://www.cnblogs.com/15fj/p/7845020.html
Copyright © 2011-2022 走看看