場景
Node的Web應用框架Express的簡介與搭建HelloWorld:
https://mp.csdn.net/console/editor/html/106650798
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
GET請求的參數的獲取
通過res.query獲取
app.get('/',(req,res)=>{ res.send(req.query); })
完整示例代碼
//引入express框架 const express = require('express'); //創建網站服務器 const app = express(); app.get('/',(req,res)=>{ res.send(req.query); }) app.listen(3000, function () { console.log('Example app listening on port 3000!') })
運行項目,瀏覽器中輸入帶參數的請求url
POST請求參數的獲取
Express中接受post請求參數需要借助第三方包 body-parser
首先在項目目錄下打開終端輸入
npm install body-parser
或者
cnpm install body-parser
然后在app.js中引入
const bodyParser = require('body-parser');
然后在創建路由時
//攔截所有請求 //extended:false 方法內部使用querystring模塊處理請求參數的格式 //extended:true 方法內部使用第三方模塊qs處理請求參數的格式 app.use(bodyParser.urlencoded({extended:false})) app.post('/add',(req,res)=>{ //接收post請求參數 res.send(req.body); })
完整示例代碼
//引入express框架 const express = require('express'); const bodyParser = require('body-parser'); //創建網站服務器 const app = express(); //攔截所有請求 //extended:false 方法內部使用querystring模塊處理請求參數的格式 //extended:true 方法內部使用第三方模塊qs處理請求參數的格式 app.use(bodyParser.urlencoded({extended:false})) app.post('/add',(req,res)=>{ //接收post請求參數 res.send(req.body); }) app.listen(3000, function () { console.log('Example app listening on port 3000!') })
為了測試post請求,在項目目錄下新建post.html
<!DOCTYPE html> <html> <head> <title>Document</title> </head> <body> <form action = "http://localhost:3000/add" method="POST"> <input type="text" name = "key"> <input type="text" name = "value"> <button type="submit">提交</button> </form> </body> </html>
在瀏覽器中打開post.html
輸入內容點擊提交