javascript
使用 NodeJS + Express 從 GET/POST Request 取值 -摘自网络
過去無論哪一種網(wǎng)站應(yīng)用程式的開發(fā)語言,初學(xué)者教學(xué)中第一次會提到的起手式,八九不離十就是 GET/POST Request 的取值。但是,在 Node.js + Express 的世界中,彷彿人人是高手,天生就會使用,從不曾看到有人撰文說明。
這應(yīng)該算是開發(fā) Web Service 的入門,在 Client 與 Server 的互動中,瀏覽器發(fā)出 GET/POST Request 時會傳值給 Server-side,常見應(yīng)用就是網(wǎng)頁上以 POST method 送出的表單內(nèi)容,或是網(wǎng)址列上的 Query Strings (ex: page?page=3&id=5)。然後,我們的網(wǎng)站應(yīng)用程式透過解析這些參數(shù),得到使用者上傳的資訊。
取得 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); });當(dāng)然也可以 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); });順帶補(bǔ)充,還有另一種方法傳遞參數(shù)給 Server,就是使用路徑的方式,可以利用 Web Server 的 HTTP Routing 來解析,常見於的各種 Web Framework。這不算是傳統(tǒng)標(biāo)準(zhǔn)規(guī)範(fàn)的做法,是屬於 HTTP Routing 的延伸應(yīng)用。
GET /hello/fred/0926xxx572 app.get('/hello/:name/:tel', function(req, res) { console.log(req.params.name); console.log(req.params.tel); });轉(zhuǎn)載于:https://www.cnblogs.com/haoliansheng/p/5594239.html
總結(jié)
以上是生活随笔為你收集整理的使用 NodeJS + Express 從 GET/POST Request 取值 -摘自网络的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 栈溢出笔记1.10 基于SEH的栈溢出
- 下一篇: JavaScript学习笔记之 数组方