express-node.js

作者: DragonRat | 来源:发表于2018-06-27 19:35 被阅读5次

烨竹

简介

express 是基于node.js web 应用程式的一种开发框架,可以快速搭建一个功能完整的网站
express.js 是建构在Node.js 中介软体模组的,我们叫它connect,它的运作就是在处理HTTP请求的函数;每处理完一个中介软体函式,会再传给下一个中间软体的函式。(更多细节请看:https://goo.gl/ryvrte

npm uninstall 模块

删除本地模块时你应该思考的问题:是否将在package.json上的相应依赖信息也消除?
npm uninstall 模块:删除模块,但不删除模块留在package.json中的对应信息
npm uninstall 模块 --save 删除模块,同时删除模块留在package.json中dependencies下的对应信息
npm uninstall 模块 --save-dev 删除模块,同时删除模块留在package.json中devDependencies下的对应信息

安装express

如果,你要globally 安装,直接在command prompt 输入

npm install -g express

Node.js 应用程式初始化,自动加入package.json

在command prompt,首先,我们建立一个资料夹:

mkdir myapp
进入该资料夹:
cd myapp
输入指令:
npm init

根据步骤,输入与这个应用程式的相关资料,它会以询答的方式让你写入一些资讯,帮你建好一个package.json,myapp这就是你的一个node.js应用程式

自动生成package文件

安装express套件

npm install express --save

安装成功

web application

1、Web Server

var express = require('express');
var app = express();
 
// define routes here..
 
var server = app.listen(5050, function () {
    console.log('Node server is running..');
});

执行结果

2、设定路由
用app.get(), app.post(), app.put(), app.delete() 定义了HTTP的GET, POST, PUT, DELETE 的路由请求

var express = require('express');
var app = express();

app.get('/', function (req, res) {
    res.send("<html><body><h1>hello world</h1></body></html>");
});
 
app.post('/submit-data', function (req, res) {
    res.send('POST Request');
});
 
app.put('/update-data', function (req, res) {
    res.send('PUT Request');
});
 
app.delete('/delete-data', function (req, res) {
    res.send('DELETE Request');
});
 
var server = app.listen(5000, function () {
    console.log('Node server is running..');
});

3、处理post请求
新建index.html

<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
<form action="/submit-student-data" method="post">
        First Name: <input name="firstName" type="text" />
        Last Name: <input name="lastName" type="text" />
<input type="submit" />
    </form>
 
</body>

添加body-parser模块(是用来解析JSON, buffer,字串,及HTTP Post请求提交的url编码资料)

 npm install body-parser -save

安装成功如下图:

添加postapp.js

var express = require('express');
var app = express();
 
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
 
app.get('/', function (req, res) {
    res.sendFile(__dirname+'/index.html');  //回应静态文件
});
 
app.post('/submit-student-data', function (req, res) {
    var name = req.body.firstName + ' ' + req.body.lastName;
 
    res.send(name + ' Submitted Successfully!');
});
 
var server = app.listen(5000, function () {
    console.log('Node server is running..');
});

4、使用静态文件app.use()

var express = require('express');
var app = express();
 
//setting middleware
app.use(express.static(__dirname + '/public')); //Serves resources from public folder
 
var server = app.listen(5050);

在myapp下新增一个public资料夹,里面存放一些静态文件

设立多个静态服务

var express = require('express');
var app = express();
 
app.use(express.static('public'));
 
//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));
 
var server = app.listen(5050);

app.use()第一个参数,images其实就像我们之前讲过的路由名称,
而实体位置是在__dirname /Images
在myapp下新增一个public资料夹,里面放入style.css;另外再新增一个Images的资料夹,里面放入图片a001.jpg

在http server提供静态服务—使用node-static
node-static module是http提供静态文件服务的模组。
安装

npm install -g node-static
cd myapp
npm install node-static --save

安装以后,我们可以使用node-static 模组了;

var http = require('http');
 
var nStatic = require('node-static');
 
var fileServer = new nStatic.Server('./public');
 
http.createServer(function (req, res) {
 
    fileServer.serve(req, res);
 
}).listen(5050);

数据库交互

Node.js支援多种不同种类的资料库主要介绍ms-sql和Mongodb
ms-sql
1、安装msql-driver

npm install mssql -g
cd myapp
npm install mssql --save

查看package.json是否安装成功;
2、建立资料库及资料表
在MS-SQL Server Management (MSSM) ,新增一个叫做SchoolDB的资料库,并且新增一个学生资料库叫做Student。如图:


添加数据:


3、连接资料库并且回应资料在网页上

var express=require('express');
var app=express();
app.get('/',function(req,res){
 var sql=require('mssql');
 
//config for your database
 var config={
    user:'sa',
    password:'justlookvvj',
    server:'localhost\\SQLEXPRESS',   //這邊要注意一下!!
    database:'SchoolDB'
 };
 
//connect to your database
 sql.connect(config,function (err) {
   if(err) console.log(err);
 
//create Request object
   var request=new sql.Request();
request.query('select * from Student',function(err,recordset){
   if(err) console.log(err);
 
//send records as a response
   res.send(recordset);
   });
 });
 
});
 
var server=app.listen(5050,function(){
 console.log('Server is running!');
});

这个例子我们载入了mssql module,并且呼叫connect()方法,透过参数config物件,去连线我们SchoolDB资料库。成功连线后,我们用sql.request物件,去执行"资料表查询",并且把资料取出来
MongoDB
MongoDB安装和操作见:https://www.jianshu.com/p/affa876ba35f
安装Mongo DB driver

npm install mongodb -g
cd myapp
npm install mongodb --save

新增数据

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

var url = 'mongodb://tester:password@localhost:27017/lxkdb';

// Use connect method to connect to the server
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
  assert.equal(null, err);
  var dbo=db.db('lxkdb');  
  dbo.collection('student',function(err,collection){
    collection.insertOne({ id:1, firstName:'Steve', lastName:'Jobs' });
    collection.insertOne({ id:2, firstName:'Bill', lastName:'Gates' });
    collection.insertOne({ id:3, firstName:'James', lastName:'Bond' });
 
    collection.countDocuments(function(err,count){
        if(err) throw err;
        console.log('Total Rows:'+count);
    });
  });

  db.close();
});

结果如图:

修改数据

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

var url = 'mongodb://tester:password@localhost:27017/lxkdb';

// Use connect method to connect to the server
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
  assert.equal(null, err);
  var dbo=db.db('lxkdb');  
  dbo.collection('student',function(err,collection){
        //collection.update
        //第一個參數是要更新的條件,第二個參數$set:更新的欄位及內容.
        //第三個參數writeConcern,第四個參數執行update後的callback函式
        collection.update({id:2},{ $set: { firstName:'James', lastName:'Gosling'} },
          {w:1}, function(err, result){
              if(err) throw err;
              console.log('Document Updated Successfully');
             });
         });

  db.close();
});

{w:1}的理解:http://aaron-joe-william.iteye.com
结果如图:

删除数据:

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

var url = 'mongodb://tester:password@localhost:27017/lxkdb';

// Use connect method to connect to the server
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
  assert.equal(null, err);
  var dbo=db.db('lxkdb');  
  dbo.collection('student',function(err,collection){
        //collection.update
        //第一個參數是要更新的條件,第二個參數$set:更新的欄位及內容.
        //第三個參數writeConcern,第四個參數執行update後的callback函式
        collection.remove({id:2},{w:1},function(err,result){
            if(err) throw err;
            console.log('Document Removed Successfully!');
        });
    });

  db.close();
});

结果如图:

查询数据

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

var url = 'mongodb://tester:password@localhost:27017/lxkdb';

// Use connect method to connect to the server
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
  assert.equal(null, err);
  var dbo=db.db('lxkdb');  
  dbo.collection('student',function(err,collection){
    collection.find({firstName:"James"}).toArray(function(err,items){
        if(err) throw err;
        console.log(items);
        console.log("We found "+items.length+" results!");
    });

});

  db.close();
});

结果如图:

!!重要!!

关于更多Collection的操作,可以参考:Collection Methods,特别在使用查询find,有不同于以往SQL的使用语法

Pug 模板引擎

相关工具:pug转html ---------html转pug
模版引擎是帮助我们以最小的code去新增一个Html Template
它可以在客户端注入一些资料(像是JSON/XML) , Html Template,透过Template Engine产生最后的HTML呈现至浏览器

安装pug样版

//cd到myapp中
npm install pug --save
//检查package.json

添加Myviews文件夹,文件夹下添加pug文件

doctype html
html
    head
        title Jade Page
    body
        h1 This page is produced by Jade engine
        p some paragraph here..

添加js文件

var express = require('express');
var app = express();
 
//set view engine
app.set("view engine","pug")

//set view directory
app.set("views","MyViews")
 
app.get('/', function (req, res) {
    res.render('sample');  // render 执行pug文件
});
 
var server = app.listen(3000, function () {
    console.log('Node server is running..');
});

综合以上,要注意的是:
1.pug template必须写在.pug档案里
2.将副档名为.pug的档案,储存在网站根目录下面的views,express 預設從views資料夾取樣版。
3.如果要自订样版存放资料夹,我们在express server必须使用app.set(“veiws","自訂樣版存放資料夾絕對路徑")

不使用express,执行样版编译

var http = require('http'); // 1 - Import Node.js core module
var jade= require('pug');
 
var data=jade.renderFile('./MyViews/sample.pug');
 
var server = http.createServer(function (req, res) {   // 2 - creating server
 
    if (req.url == '/') { //check the URL of the current request
        // set response header
        res.writeHead(200, { 'Content-Type': 'text/html' });
        // set response content
        res.write(data);
        res.end();
    }else
        res.end('Invalid Request!');
});
 
server.listen(3000); //3 - listen for any incoming requests 
console.log('Node.js web server at port 3000 is running..')

除了汉字出现乱码没什么差别,如图

pug语法参考:https://pugjs.org/api/getting-started.html

pug与mysql交互(哈哈。其实本人对mysql比较有好感)

样板语法测试:http://naltatis.github.io/jade-syntax-docs/这个网站你肯定会用到的;

cd myapp
npm install mssql --save

pug

doctype html
html
head
title=title
body
    h1  mysql数据取出
 
    ul
        each item in catenameList
            li=item.catename

js

var express=require('express');
var app=express();
 
//set view engine
app.set("view engine","pug")
//set view directory
app.set("views","MyViews")
 
app.get('/',function(req,res){
    var mysql=require('mysql');
    //config for your database
    var con = mysql.createConnection({
        host: "localhost",
        user:'root',
        password:'root',
        database:'blog'
    });
    //connect to your database
    con.connect(function (err) {
        if(err) console.log(err);
        con.query('select catename from tp_cate',function(err,recordset){
            if(err)
                console.log(err);
            else
              res.render('sample',{catenameList:recordset});
        });
    });
 
});
 
var server=app.listen(3000,function(){
    console.log('Server is running!');
});

执行结果如下:

更多操作:https://www.w3schools.com/nodejs/nodejs_mysql_select.asp

Pug与mongodb交互

连接mongodb,取得资料

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');



// Use connect method to connect to the server
module.exports.personList=function(callback){
    MongoClient.connect('mongodb://tester:password@localhost:27017/lxkdb'url,{ useNewUrlParser: true }, function(err, db) {
    assert.equal(null, err);
    var dbo=db.db('lxkdb');  
    dbo.collection('student',function(err,collection){
        collection.find({firstName:"James"}).toArray(function(err,items){
            if(err) throw err;
                db.close();
                callback(items);
        });

    });

    
    });
}

建立模板

doctype html
html
head
title=title
body
    h1 mongodb与pug交互
 
    ul
      for item in personList
        li= item.id + ":"
         p=item.firstName +' '+item.lastName

连接MongoDB,在express执行样版编绎,呈现资料

var mongodata=require('./app.js');
var express=require("express");
var app=express();
 
//set view engine
app.set("view engine","pug")
//set view directory
app.set("views","MyViews")
 
mongodata.personList(function(recordset){
    //console.log(recordset);
    app.get('/',function(req,res){
    res.render('sample', { personList:recordset });
   });
 
});
 
var server=app.listen(3000,function(){
    console.log('Server is running!');
});

执行如图:

pug引用bootstrap

下面用bootstraps制作页头页脚(layout)
寻找Bootstrap框架
首先,我们可以进入网站getbootstrap,点取上方连结Getting started,可以找到喜欢的框架版型

进入获取源码

将Html转换成Jade
进入http://html2jade.vida.io/

将转换好的额pug文件略作修改:放入layout.pug文件

编写js代码

//postapp.js
var mongodata=require('./app.js');
var express=require("express");
var app=express();
 
//set view engine
app.set("view engine","pug")
//set view directory
app.set("views","MyViews")
 //样式引用
app.use(express.static('public'));
mongodata.personList(function(recordset){
    //console.log(recordset);
    app.get('/',function(req,res){
    res.render('sample', { personList:recordset });
   });
 
});
 
var server=app.listen(3000,function(){
    console.log('Server is running!');
});
//app.js
var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');



// Use connect method to connect to the server
module.exports.personList=function(callback){
    MongoClient.connect('mongodb://tester:password@localhost:27017/lxkdb',{ useNewUrlParser: true }, function(err, db) {
    assert.equal(null, err);
    var dbo=db.db('lxkdb');  
    dbo.collection('student',function(err,collection){
        collection.find({firstName:"James"}).toArray(function(err,items){
            if(err) throw err;
                db.close();
                callback(items);
        });

    });

    
    });
}

套用layout的pug

extends ./layout
 
block page-header
    h1 pug与bootstrap-------二哈
 
block content
    ul
      for item in personList
        li= item.id + ":"
         p=item.firstName +' '+item.lastName

执行如下:

相关文章

  • express-node.js

    烨竹 简介 express 是基于node.js web 应用程式的一种开发框架,可以快速搭建一个功能完整的网站e...

  • Express-node.js框架学习笔记

    知识点: (1)路由 app.get 或者 app.post,来访问 正则表达式 /^ $/ req.param...

网友评论

    本文标题:express-node.js

    本文链接:https://www.haomeiwen.com/subject/vdqiyftx.html