Express请求处理-GET和POST请求参数的获取
生活随笔
收集整理的這篇文章主要介紹了
Express请求处理-GET和POST请求参数的获取
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
場景
Node的Web應(yīng)用框架Express的簡介與搭建HelloWorld:
Node的Web應(yīng)用框架Express的簡介與搭建HelloWorld_霸道流氓氣質(zhì)的博客-CSDN博客
注:
博客:
霸道流氓氣質(zhì)的博客_CSDN博客-C#,架構(gòu)之路,SpringBoot領(lǐng)域博主
關(guān)注公眾號
霸道的程序猿
獲取編程相關(guān)電子書、教程推送與免費(fèi)下載。
實(shí)現(xiàn)
GET請求的參數(shù)的獲取
通過res.query獲取
app.get('/',(req,res)=>{res.send(req.query); })完整示例代碼
//引入express框架 const express = require('express');//創(chuàng)建網(wǎng)站服務(wù)器 const app = express(); app.get('/',(req,res)=>{res.send(req.query); })app.listen(3000, function () {console.log('Example app listening on port 3000!') })運(yùn)行項(xiàng)目,瀏覽器中輸入帶參數(shù)的請求url
POST請求參數(shù)的獲取
Express中接受post請求參數(shù)需要借助第三方包 body-parser
首先在項(xiàng)目目錄下打開終端輸入
npm install body-parser或者
cnpm install body-parser然后在app.js中引入
const bodyParser = require('body-parser');然后在創(chuàng)建路由時(shí)
//攔截所有請求 //extended:false 方法內(nèi)部使用querystring模塊處理請求參數(shù)的格式 //extended:true 方法內(nèi)部使用第三方模塊qs處理請求參數(shù)的格式 app.use(bodyParser.urlencoded({extended:false})) app.post('/add',(req,res)=>{//接收post請求參數(shù)res.send(req.body); })完整示例代碼
//引入express框架 const express = require('express'); const bodyParser = require('body-parser'); //創(chuàng)建網(wǎng)站服務(wù)器 const app = express();//攔截所有請求 //extended:false 方法內(nèi)部使用querystring模塊處理請求參數(shù)的格式 //extended:true 方法內(nèi)部使用第三方模塊qs處理請求參數(shù)的格式 app.use(bodyParser.urlencoded({extended:false})) app.post('/add',(req,res)=>{//接收post請求參數(shù)res.send(req.body); })app.listen(3000, function () {console.log('Example app listening on port 3000!') })為了測試post請求,在項(xiàng)目目錄下新建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
輸入內(nèi)容點(diǎn)擊提交
總結(jié)
以上是生活随笔為你收集整理的Express请求处理-GET和POST请求参数的获取的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Express请求处理-构建模块化路由
- 下一篇: PostMan怎样携带登录信息请求后台接