Express请求处理-GET和POST请求参数的获取
生活随笔
收集整理的這篇文章主要介紹了
Express请求处理-GET和POST请求参数的获取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景
Node的Web應用框架Express的簡介與搭建HelloWorld:
Node的Web應用框架Express的簡介與搭建HelloWorld_霸道流氓氣質的博客-CSDN博客
注:
博客:
霸道流氓氣質的博客_CSDN博客-C#,架構之路,SpringBoot領域博主
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
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
輸入內容點擊提交
總結
以上是生活随笔為你收集整理的Express请求处理-GET和POST请求参数的获取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Express请求处理-构建模块化路由
- 下一篇: PostMan怎样携带登录信息请求后台接