Node.js中的express架構擷取http參數

來源:互聯網
上載者:User

標籤:

最近本人在學習開發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代碼

<form action="/index" method="get">  
       <input type="text" name="login_name"/>  
     <input type="submit" value="Sign In" />  
</form> 
在nodeJs中我們要自訂HTTP,因此建立index.js
var app = require(‘express‘).createServer();  
  
app.get(‘/:key‘, function(req, res){  
  console.log(req.params.key);//輸出index   
  console.log(req.query.login_name);//輸出表單get提交的login_name   
  res.send(‘great you are right for get method!‘);//顯示頁面文字資訊   
});  
app.post(‘/:key‘, function(req, res){  
<pre name="code" class="javascript">  console.log(req.params.key);//輸出index   
  console.log(req.body.login_name);//輸出表單post提交的login_name   
  res.send(‘great you are right for post method!‘);//顯示頁面文字資訊 
});app.listen(3000);

之後運行node index.js就可以看到本效果,當然前提是你要先訪問test.html,至於如何通過express訪問一個html檔案我就不詳細描述了,可以參考如下代碼:
global.fs=require(‘fs‘);          
var realpath = VIEW + "test.html";  
var file = fs.readFileSync(realpath);  
res.end(file); 
更多關於Node.js的詳細資料,或者請點這裡

本篇文章來源於 Linux公社網站(www.linuxidc.com)  原文連結:http://www.linuxidc.com/Linux/2012-04/58730.htm

Node.js中的express架構擷取http參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.