Node.js express擷取參數有三種方法

來源:互聯網
上載者:User

標籤:提交   action   blog   模式   check   ref   title   客戶   params   

Node.js express擷取參數有三種方法

 

近本人在學習開發NodeJs,使用到express架構,對於網上的學習資料甚少,因此本人會經常在開發中做一些總結。

express擷取參數有三種方法:官網介紹如下

 

  • Checks route params (req.params), ex: /user/:id
  • Checks query string params (req.query), ex: ?id=12
  • Checks urlencoded body params (req.body), ex: id=

1、例如:127.0.0.1:3000/index,這種情況下,我們為了得到index,我們可以通過使用req.params得到,通過這種方法我們就可以很好的處理Node中的路由處理問題,同時利用這點可以非常方便的實現MVC模式;

 

2、例如:127.0.0.1:3000/index?id=12,這種情況下,這種方式是擷取用戶端get方式傳遞過來的值,通過使用req.query.id就可以獲得,類似於PHP的get方法;

3、例如:127.0.0.1:300/index,然後post了一個id=2的值,這種方式是擷取用戶端post過來的資料,可以通過req.body.id擷取,類似於PHP的post方法;

 

下面舉例介紹下這三個方法:

如下一個test.html代碼

  1. <form action="/index" method="get">  
  2.        <input type="text" name="login_name"/>  
  3.      <input type="submit" value="Sign In" />  
  4. </form>  

在nodeJs中我們要自訂HTTP,因此建立index.js

  1. var app = require(‘express‘).createServer();  
  2.   
  3. app.get(‘/:key‘, function(req, res){  
  4.   console.log(req.params.key);//輸出index   
  5.   console.log(req.query.login_name);//輸出表單get提交的login_name   
  6.   res.send(‘great you are right for get method!‘);//顯示頁面文字資訊   
  7. });  
  8. app.post(‘/:key‘, function(req, res){  
  9. <pre name="code" class="javascript">  console.log(req.params.key);//輸出index   
  10.   console.log(req.body.login_name);//輸出表單post提交的login_name   
  11.   res.send(‘great you are right for post method!‘);//顯示頁面文字資訊  

});app.listen(3000);


 


之後運行node index.js就可以看到本效果,當然前提是你要先訪問test.html,至於如何通過express訪問一個html檔案我就不詳細描述了,可以參考如下代碼:

  1. global.fs=require(‘fs‘);          
  2. var realpath = VIEW + "test.html";  
  3. var file = fs.readFileSync(realpath);  
  4. res.end(file);  

 

http://blog.csdn.net/junshao90/article/details/8209166

Node.js express擷取參數有三種方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.