使用 NodeJS + Express 從 GET/POST Request 取值 -摘自网络

過去無論哪一種網站應用程式的開發語言,初學者教學中第一次會提到的起手式,八九不離十就是 GET/POST Request 的取值。但是,在 Node.js + Express 的世界中,彷彿人人是高手,天生就會使用,從不曾看到有人撰文說明。

這應該算是開發 Web Service 的入門,在 Client 與 Server 的互動中,瀏覽器發出 GET/POST Request 時會傳值給 Server-side,常見應用就是網頁上以 POST method 送出的表單內容,或是網址列上的 Query Strings (ex: page?page=3&id=5)。然後,我們的網站應用程式透過解析這些參數,得到使用者上傳的資訊。

取得 GET Request 的 Query Strings:

GET /test?name=fred&tel=0926xxx572

app.get('/test', function(req, res) {
    console.log(req.query.name);
    console.log(req.query.tel);
});

如果是透過表單且是用 POST method:

<form action='/test' method='post'> 
    <input type='text' name='name' value='fred'> 
    <input type='text' name='tel' value='0926xxx572'> 
    <input type='submit' value='Submit'> 
</form>
app.post('/test', function(req, res) {
    console.log(req.query.id);
    console.log(req.body.name);
    console.log(req.body.tel);
});

當然也可以 Query Strings 和 POST method 的表單同時使用:

<form action='/test?id=3' method='post'> 
    <input type='text' name='name' value='fred'> 
    <input type='text' name='tel' value='0926xxx572'> 
    <input type='submit' value='Submit'> 
</form>
app.post('/test', function(req, res) {
    console.log(req.query.id);
    console.log(req.body.name);
    console.log(req.body.tel);
});

順帶補充,還有另一種方法傳遞參數給 Server,就是使用路徑的方式,可以利用 Web Server 的 HTTP Routing 來解析,常見於的各種 Web Framework。這不算是傳統標準規範的做法,是屬於 HTTP Routing 的延伸應用。

GET /hello/fred/0926xxx572

app.get('/hello/:name/:tel', function(req, res) {
    console.log(req.params.name);
    console.log(req.params.tel);
});  
原文地址:https://www.cnblogs.com/haoliansheng/p/5594239.html