使用 NodeJS + Express 從 GET/POST Request 取值
发布于 11 年前 作者 duyinghua 144566 次浏览 最后一次编辑是 8 年前

過去無論哪一種網站應用程式的開發語言,初學者教學中第一次會提到的起手式,八九不離十就是 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);
});

来源:http://liuxufei.com/blog/jishu/798.html

9 回复

是啊. 入门的文章太少了, 摸了好久的 别忘了 app.use(express.bodyParser());

总结一下,是不是应该就三种:

  1. req.params.xxxxx 从path中的变量
  2. req.query.xxxxx 从get中的?xxxx=中
  3. req.body.xxxxx 从post中的变量

我也是这么认为的

express 还可以 req.param(“id”) GET/POST都适用吧?

欢迎补充,是的没有问题的,刚试过三种方式的参数都可以 req.param() 这样得到

楼主台湾人?

回到顶部