開始nodejs+express的學習+實踐(2)

1.路由處理php

咱們經過訪問 http://localhost:1234/已經顯示了默認首頁內容。css

咱們打開app.js文件,看路由處理部分代碼:html

咱們知道請求方式有get和post,咱們當前的方式是get請求,而且請求項目路徑是 「/」node

在程序中咱們能夠看到,當地址是「/」時,會調用routers.index的處理,這是文件模塊的定義express

咱們打開routes目錄下的文件模塊,查看代碼程序:npm

 

咱們此時會比較疑惑,經過require加載的模塊代碼是這樣的:json

var routes = require('./routes');

其實這個方法會自動去找下面的index.js文件,咱們改寫成這樣一樣能夠,爲了理解方便api

var routes = require('./routes/index');

後綴名可缺省,大部分的模塊都是js文件,會自動識別。數組

修改後,咱們能夠ctrl+c結束,而後npm start從新啓動,地址刷新發現是沒有問題的。瀏覽器

這裏咱們知道,咱們寫的文件模塊會掛在 exports或者module.exports對象下,就能夠經過require()獲取到。

如今咱們已經知道,訪問根目錄「/」,會調用index.js的index方法,咱們看到方法裏面的處理程序是:

res.render('index', { title: 'Express' });

req和res對象很少說,利用http模塊建立服務器已經很是熟悉,在這裏express對兩個對象作了更多的包裝,

打開express的api手冊,咱們查看說明:http://www.expressjs.com.cn/4x/api.html#res.render

 

在手冊咱們能夠看到,res的render方法有三個參數,

arg1:使用的模板引擎名稱(就是調用那個引擎頁面,咱們的ejs)

arg2:就是傳入引擎的內容({}類型),

arg3:錯誤時執行的回調

看到這裏咱們幾乎就明白了,咱們訪問「/」會使用index的模板頁面,而且穿入模板的內容:鍵是title值是express,咱們把

 res.render('index', { title: 'Express' });

修改成:

 res.render('index', { title: 'Express',hello:'hello world!' });

既然這裏會模板index傳入數據,那麼模板index確定要接收和處理數據,咱們打開index模板頁面:

如今是title的顯示,咱們修改index.ejs代碼,加入hello的顯示,與路由處理同步

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <p><%= hello %></p>
  </body>
</html>

重啓運行,刷新瀏覽器,會看到傳入的新數據:

 

 咱們一個網站確定會有多個網頁,之間進行跳轉操做,固然這就是路由的功能了,咱們如今訪問的根路徑是「/」,此時咱們須要多一些頁面來了解路由的工做處理。

咱們修改index.ejs頁面,加入一些a標籤作跳轉演示

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <p><a href="/hello"><%= hello %></a></p>
  </body>
</html>

此時咱們點擊「hello world」會跳轉到「/hello」頁面,好了咱們此時要加入對「/hello」的路由處理了

app.js加入理由處理:

index.js加入處理程序:

/* GET home page. */
exports.index = function(req, res){
    res.render('index', { title: 'Express',hello: 'hello world!' });
};
/* GET hello page. */
exports.hello = function(req, res){
    res.render('hello', { text: '麼麼噠' });
};

咱們會往hello.ejs模板頁面傳入「麼麼噠」,咱們建立hello.ejs,寫入代碼:

經過index.ejs複製修改便可,從路由,處處理,到模板所有書寫完畢,咱們重啓後,刷新頁面,點擊測試!

彷佛沒有問題了,不過咱們頁面會有大量的路由處理,若是咱們所有放在app.js,會發現如入口文件愈來愈大,愈來愈混雜,咱們最好是把路由的處理分離處理,單獨在一個模塊去處理,

其實路由的處理,就是調用app對象,咱們只要把app對象做爲參數傳入到外面,彷佛就實現分離了,咱們對index.js作修改,把app對象傳入到index.js頁面

修改後咱們的全部路由處理就所有在index.js進行了,index.js代碼:

function rout(app){
    app.get('/',function(req, res){
        res.render('index', { title: 'Express',hello: 'hello world!' });
    });
    app.get('/hello',  function(req, res){
        res.render('hello', { text: '麼麼噠' });
    });
};
exports.rout=rout;

咱們要在app.js調用index的程序和傳入app對象,app.js修改以下:

重啓,運行,若是報錯要本身查看是否書寫錯誤。

2.ejs模板引擎的瞭解和處理

咱們上面其實已經使用和簡單瞭解的ejs的使用,咱們爲何可使用ejs,不要深究,咱們知道在哪裏引入就能夠了,

咱們在app.js能夠看到下面的代碼:

__dirname是node的全局變量,會獲取到當前文件的目錄,不要深刻理解了,知道就好!

咱們對比路由頁面和模板頁面程序:

 

這很是清晰了吧,res.render發出的數據會被模板介紹和顯示,中間的橋就是那個鍵名,而且ejs是在<% %>放程序代碼的,

裏面的「=」其實就等同於php的echo。

其實如今咱們發送的都是單一數據,能夠說是1,其實不少時候是n,當時就是數組的形式了,咱們修改index.js的根路由控制

咱們要利用ejs來顯示數組形式的數據了,修改index.ejs的代碼:http://www.embeddedjs.com/

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <p><a href="/hello"><%= hello %></a></p>
    <ul>
        <% for(var i=0; i<arr.length; i++) {%>
        <li><%= arr[i] %></li>
        <% } %>
    </ul>
  </body>
</html>

其實語法和js沒太大區別,咱們看看就知道了,

重啓運行,刷新頁面查看:

固然還有if的處理等,咱們遇到在查看手冊就能夠!

3.get/post參數獲取和路徑跳轉

=====首先是get的參數獲取,咱們看手冊地址:

獲取get參數有2中方法,其實利用req.query獲取的感受更加常見,咱們知道參數的地址通常以下:

localhost:80/peo?a="123"&b="999"

而後咱們獲取a和b的參數值就能夠了,不過express還提供了後面作路徑的處理方法,也就是req.params,

localhost:80/peo/123 把123做爲參數值,這個其實針對只有一個參數的是很方便的,多個參數咱們仍是要利用req.query

其實用什麼仍是看你的設計和處理,適合就行。

針對get請求,?的形式就不用過多解釋,咱們分析把路徑作參數的處理方式

把路徑做爲參數內容,在路由處理時,要用:xx的形式,xx可使用req.params.xx獲取到參數值。

咱們修改index.ejs代碼,測試路徑作參數的處理操做:

咱們鼠標hover在列表連接上會看到地址以下:

localhost:1234/list/0

localhost:1234/list/1

localhost:1234/list/2 ......

咱們既然把路徑作參數,那麼0-x就是參數值了,我麼要在路由進行獲取和處理:

咱們加入處理,修改index.js:

咱們建立list.ejs,顯示內容:

<!DOCTYPE html>
<html>
  <head>
    <title>list</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= text %></h1>
  </body>
</html>

重啓,運行,咱們點擊列表,會發現點擊進入的頁面會把路徑作參數獲取和顯示在頁面內部:

 

其實這樣處理的方式比較少見,參數大部分都是以?key1=val1&key2=val2的形式

咱們修改index.ejs代碼,改成常見形式:

咱們的路由處理,進行修改:

咱們發現和使用上面的方法結果是同樣的,這樣看起來更常見。

=====下面咱們處理post請求參數

其實post和get區別不是很大,不過通常使用post處理的數據都是隱性的,咱們就用登陸作處理演示:

1.有一個登陸界面,

1.咱們建立login.ejs

2.路由加入 get的/login處理,指向login.ejs

3.登陸時 作post處理,咱們加入post的logincheck路由處理

4.logincheck路由會獲取參數,成功會跳到根目錄,失敗跳到login目錄

開始書寫程序:

login.ejs代碼以下:

<!DOCTYPE html>
<html>
  <head>
    <title>login</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
  <form  method="post" action="/logincheck">
      <input type="text" placeholder="用戶名" name="user">
      <input type="password" placeholder="密碼"  name="pass">
      <input id="ok" type="submit" value="登陸">
  </form>
  </body>
</html>

路由文件index.js加入處理:

重啓,運行,地址敲入:http://localhost:1234/login

咱們就會看到登陸界面了:

咱們點擊登陸,看看有何變化,會提示404,咱們沒有對/logincheck作路由處理,咱們在index.js加入處理,post操做

此時問題出現了,怎麼獲取參數,這個比較簡單,而後怎麼跳轉?

先獲取參數,

req.body.user和req.body.pass就獲取到了用戶名和密碼。

咱們能夠寫一個死判斷就是用戶名等於「tom」和密碼等於"tom"算登陸成功,成功跳轉,其餘失敗!

路由修改:

    app.post('/logincheck',  function(req, res){
       var user= req.body.user;
       var pass= req.body.pass;
        if(user=="tom" && pass=="tom"){
        }else{
        };
    });

裏面在寫跳轉就能夠了,就和php的header方法同樣,

咱們在手冊查看跳轉方法:

咱們修改路由處理以下:

    app.post('/logincheck',  function(req, res){
       var user= req.body.user;
       var pass= req.body.pass;
        if(user=="tom" && pass=="tom"){
            res.redirect('/');
        }else{
            res.redirect('/login');
        };
    });

重啓,運行,若是用戶名和密碼都是tom就會跳轉到首頁面了。

4.總結

到這裏,咱們的基本處理都結束了,添加和修改了不少文件,我在下面把源碼粘貼出來!

app.js:修改比較少,主要是把app對象傳出

var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/user');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
routes.rout(app);
app.get('/users', users.list);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

index.js:修改較多,多個路由分析

function rout(app){
    app.get('/',function(req, res){
        res.render('index', { title: 'Express',hello: 'hello world!',arr:[111111,2222,33333,44444] });
    });
    app.get('/hello',  function(req, res){
        res.render('hello', { text: '麼麼噠' });
    });
    app.get('/list',  function(req, res){
        res.render('list', { text: req.query.id });
    });
    app.get('/login',  function(req, res){
        res.render('login');
    });
    app.post('/logincheck',  function(req, res){
       var user= req.body.user;
       var pass= req.body.pass;
        if(user=="tom" && pass=="tom"){
            res.redirect('/');
        }else{
            res.redirect('/login');
        };
    });
};
exports.rout=rout;

index.ejs

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <p><a href="/hello"><%= hello %></a></p>
    <ul>
        <% for(var i=0; i<arr.length; i++) {%>
        <li><a href="/list?id=<%= i %>"><%= arr[i] %></a></li>
        <% } %>
    </ul>
  </body>
</html>

list.ejs

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <p><a href="/hello"><%= hello %></a></p>
    <ul>
        <% for(var i=0; i<arr.length; i++) {%>
        <li><a href="/list?id=<%= i %>"><%= arr[i] %></a></li>
        <% } %>
    </ul>
  </body>
</html>

hello.ejs

<!DOCTYPE html>
<html>
  <head>
    <title>hello</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= text %></h1>
  </body>
</html>

login.ejs

<!DOCTYPE html>
<html>
  <head>
    <title>login</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
  <form  method="post" action="/logincheck">
      <input type="text" placeholder="用戶名" name="user">
      <input type="password" placeholder="密碼"  name="pass">
      <input id="ok" type="submit" value="登陸">
  </form>
  </body>
</html>

www目錄下端口爲1234

相關文章
相關標籤/搜索