聲明:轉(zhuǎn)載請注意出處
技術(shù)交流:
微信公眾號:北piao青年
EMAIL: hoojiaxin@hotmail.com
獲取GET請求參數(shù)
1、關(guān)于get請求
一般在web應(yīng)用開發(fā)中姓赤,get都用作數(shù)據(jù)獲取和查詢,服務(wù)器根據(jù)查詢請求的參數(shù)從數(shù)據(jù)庫或其他地方查詢數(shù)據(jù)共啃,將數(shù)據(jù)返回給調(diào)用者;而查詢的參數(shù)是在URL上進行的
http://localhost:3000/login?username=david&password=123456
2暂题、獲取前端get請求
通過req.query可以獲得用戶發(fā)送的get請求移剪,之后通過查詢數(shù)據(jù)庫將相應(yīng)數(shù)據(jù)返回給調(diào)用者。
http://localhost:3000/login?username=david&password=123456
參數(shù)獲取
//req.query會獲取全部的請求參數(shù)
let params = req.query;
//單獨獲取某一個參數(shù)
let username = req.query.username;
let password = req.query.password;
3薪者、GET請求實例
需求:我們通過發(fā)送一個請求纵苛,攜帶參數(shù)username和password,在服務(wù)器解析后并返回
定義請求路由
app.get('/login',function(req,res,next){
res.send(req.query)
})
雖然獲取get參數(shù)并不復(fù)雜,但使用頻率卻相當(dāng)?shù)母吖ト耍瑢τ谌魏渭夹g(shù)我們都應(yīng)該秉持認真的態(tài)度去了解和學(xué)習(xí)它取试。
獲取POST請求參數(shù)
1、關(guān)于POST請求
post方法作為http請求很重要的一部分怀吻,幾乎所有的網(wǎng)站都有用到它瞬浓,與get不同,post請求更像是在服務(wù)器上做修改操作蓬坡,它一般用于數(shù)據(jù)資源的更新猿棉。相比于get請求,post所請求的數(shù)據(jù)會更加安全屑咳。get請求會在地址欄url中顯示輸入的用戶名和密碼(有中文時會轉(zhuǎn)化為BASE64加密)萨赁,而post請求則會將數(shù)據(jù)放入http請求包的請求體中,這使得別人無法直接看到用戶名和密碼兆龙!
2杖爽、Express如何設(shè)置POST請求
2.1 前端使用POST方式請求
設(shè)置form表單請求為post方法,enctype屬性一般設(shè)置為“application/x-www-form-urlencoded”详瑞,如果設(shè)置成multipart/form-data掂林,則多用于文件上傳
<form action="/login" method="post" enctype="application/x-www-form-urlencoded">
</form>
2.2 設(shè)置解析body中間件
express 無法直接獲取Post請求的參數(shù)臣缀,需要設(shè)置body解析中間件
app.use(express.urlencoded())
2.3 獲取POST請求body數(shù)據(jù)
app.post('/login',function(req,res,next){
let username = req.body.username;
let password = req.body.password;
res.send(req.body)
})
3坝橡、POST請求案例
需求:使用Post請求表單提交“用戶名”和“密碼”參數(shù),服務(wù)器解析Post請求Body中的數(shù)據(jù)精置,并將參數(shù)返回
登錄頁面login.ejs
<!DOCTYPE html>
<html>
<head>
<title>登錄</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<div style="width:300px;text-align: center;">
<h1>登錄</h1>
<form action="/login" method="POST" enctype="application/x-www-form-urlencoded">
用戶名:<input type="text" name="username"></br>
密碼:<input type="password" name="password"></br>
<input type="submit" value="登錄">
</form>
</div>
</body>
</html>
創(chuàng)建接收請求的路由
var express = require('express');
var path = require('path');
var app = express();
// 設(shè)置模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//設(shè)置body解析中間件
app.use(express.urlencoded())
//接收/login GET請求计寇,返回登錄頁面login.ejs
app.get('/login',function(req,res,next){
res.render('login')
})
//接收/login POST請求
app.post('/login',function(req,res,next){
let username = req.body.username;
let password = req.body.password;
res.send(req.body)
})
module.exports = app;