本篇文章帶大家了解一下node.js中的熱重啟、get請求、post請求和中間件,希望對大家有所幫助!
一、node熱重啟
1.安裝
npm i nodemon
2.運行啟動
nodemon .bin/www
二、關(guān)于get請求
一般在網(wǎng)站開發(fā)中,get都用作數(shù)據(jù)獲取和查詢,類似于數(shù)據(jù)庫中的查詢操作,當(dāng)服務(wù)器解析前臺資源后即傳輸相應(yīng)內(nèi)容;而查詢字符串是在URL上進行的,形如:
http://localhost:8080/login?goods1=0001&goods2=0002
獲取前臺get請求
通過req.query可以獲得用戶發(fā)送的get請求,之后通過node操作將相應(yīng)數(shù)據(jù)返回給用戶。
如果發(fā)送的是:
http://localhost:8080/login?goods1=0001&goods2=0002
響應(yīng)的話則通過:
req.query
他會獲取到全部數(shù)據(jù),或
req.query.goods1 req.query.goods2
來單獨或去每一個數(shù)據(jù)??傊煌男枨髮?yīng)不同的業(yè)務(wù),大家按自己的需要來獲?。?/p>
實例
下面通過一個實例來對獲取get參數(shù)進行一個總結(jié):
HTML:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <form action="http://localhost:8080/login" method="get"> 用戶: <input type="text" name="user" id="user" placeholder="用戶名"/> <br> 密碼: <input type="password" name="password" id="password" placeholder="密碼"/> <br> <input type="submit" value="提交"/> </form> </body> </html>
node:
const express = require("express"); var app = express(); app.get("/",function(req,res){ res.send("主頁"); }); app.get("/login",function(req,res){ console.log(req.query); res.send("登錄路由,user為:"+req.query.user+"==> password為:"+req.query.password); }); app.listen(8080);
三、關(guān)于POST請求
post方法作為http請求很重要的一部分,幾乎所有的網(wǎng)站都有用到它,與get不同,post請求更像是在服務(wù)器上做修改操作,它一般用于數(shù)據(jù)資源的更新。 相比于get請求,post所請求的數(shù)據(jù)會更加安全。上一章中我們發(fā)現(xiàn)get請求會在地址欄顯示輸入的用戶名和密碼(有中文時會轉(zhuǎn)化為BASE64加密),而post請求則會將數(shù)據(jù)放入http包的包體中,這使得別人無法直接看到用戶名和密碼!
Express如何設(shè)置POST請求
1.首先我們得知道在form表單進行post請求,enctype
屬性一般設(shè)置為“application/x-www-form-urlencoded
”,如果設(shè)置成multipart/form-data
,則多用于文件上傳,如下:
<form action="#" method="post" enctype="application/x-www-form-urlencoded"> </form>
2.設(shè)置解析body中間件
app.use(express.urlencoded())
3.獲取body數(shù)據(jù)
req.body.username
登陸案例:
HTML:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>登陸</h1> <form action="/login" method="POST"> <div> 用戶名:<input type="text" name="username"> </div> <div> 密碼:<input type="password" name="password"> </div> <button>登陸</button> </form> </body> </html>
APP.JS
var express = require('express'); var path = require('path') var app = express(); var sqlQuery = require('./lcMysql') // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(express.static(path.join(__dirname, 'public'))); //解析post提交的數(shù)據(jù) app.use(express.urlencoded()) //搜索首頁 app.get('/',(req,res)=>{ res.render('index.ejs') }) //登陸頁 app.get('/login',(req,res)=>{ res.render('login') }) //處理登陸請求 app.post('/login',async (req,res)=>{ //獲取用戶名和密碼 let username = req.body.username let password = req.body.password //查詢數(shù)據(jù)庫是否由此用戶名和密碼 let sqlStr = 'select * from user where username = ? and password = ?'; let arr = [username,password]; let result = await sqlQuery(sqlStr,arr) if(result.length == 0 ){ res.send("登陸失敗") }else{ res.send("登陸成功") } }) module.exports = app;
四、中間件
從字面意思,我們可以了解到它大概就是做中間代理操作,事實也是如此;大多數(shù)情況下,中間件就是在做接收到請求和發(fā)送響應(yīng)中間的一系列操作。事實上,express是一個路由和中間件的web框架,Express 應(yīng)用程序基本上是一系列中間件函數(shù)的調(diào)用。
1.瀏覽器發(fā)送請求
2.express接受請求
中間處理的過程
3.路由函數(shù)處理渲染(req,res)
4.res.render渲染
中間件函數(shù)可以執(zhí)行以下任務(wù):
- 執(zhí)行任何代碼。
- 對請求和響應(yīng)對象進行更改。
- 結(jié)束請求/響應(yīng)循環(huán)。
- 調(diào)用堆棧中的下一個中間件函數(shù)。
中間件也分為應(yīng)用層中間件、路由中間件、內(nèi)置中間件、錯誤處理中間件和第三方中間件。下面分別對以下進行說明:
1.應(yīng)用層中間件
應(yīng)用級中間鍵綁定到app對象使用app.use和app.METHOD()-需要處理http請求的方法,例如GET、PUT、POST,將之前的get或者post替換為use就行。 例如下面實例:
const express=require("express"); var app=express(); //匹配路由之前的操作 app.use(function(req,res,next()){ console.log("訪問之前"); }); app.get("/",function(req,res){ res.send("主頁"); }); app.listen(8080);
這時我們會發(fā)現(xiàn)http://localhost:8080/地址一直在加載,但命令行里顯示了“訪問之前”,說明程序并不會同步執(zhí)行,如果使用next來是路由繼續(xù)向下匹配,那么就能又得到主頁數(shù)據(jù)了:
const express=require("express"); var app=express(); //匹配路由之前的操作 app.use(function(req,res,next){ console.log("訪問之前"); next(); }); app.get("/",function(req,res){ res.send("主頁"); }); app.listen(8080);
當(dāng)然也可以簡化寫法:
const express=require("express"); var app=express(); app.use(function(req,res,next){ console.log("訪問之前"); next(); },function(req,res){ res.send("主頁"); }); app.listen(8080);
因此,在進行路由匹配之前或再錄又要繼續(xù)向下執(zhí)行時想做個操作,那么應(yīng)用層中間件無疑是好的選擇。
2.路由中間件
路由級中間件和應(yīng)用級中間件類似,只不過他需要綁定express.Router();
var router = express.Router()
在匹配路由時,我們使用 router.use() 或 router.VERB() ,路由中間件結(jié)合多次callback可用于用戶登錄及用戶狀態(tài)檢測。
const express = require("express"); var app = express(); var router=express.Router(); router.use("/",function(req,res,next){ console.log("匹配前"); next(); }); router.use("/user",function(req,res,next){ console.log("匹配地址:",req.originalUrl); next(); },function(req,res){ res.send("用戶登錄"); }); app.use("/",router); app.listen(8080);
總之在檢測用戶登錄和引導(dǎo)用戶應(yīng)該訪問哪個頁面是,路由中間件絕對好用。
3.錯誤處理中間件
顧名思義,它是指當(dāng)我們匹配不到路由時所執(zhí)行的操作。錯誤處理中間件和其他中間件基本一樣,只不過其需要開發(fā)者提供4個自變量參數(shù)。
app.use((err, req, res, next) => { res.sendStatus(err.httpStatusCode).json(err); });
一般情況下,我們把錯誤處理放在最下面,這樣我們即可對錯誤進行集中處理。
const express=require("express"); var app=express(); app.get("/",function(req,res,next){ const err=new Error('Not Found'); res.send("主頁"); next(err); }); app.use("/user",function(err,req,res,next){ console.log("用戶登錄"); next(err); },function(req,res,next){ res.send("用戶登錄"); next(); }); app.use(function(req,res){ res.status(404).send("未找到指定頁面"); }); app.listen(8080);
4.內(nèi)置中間件
從版本4.x開始,Express不再依賴Content,也就是說Express以前的內(nèi)置中間件作為單獨模塊,express.static是Express的唯一內(nèi)置中間件。
express.static(root, [options]);
通過express.static我們可以指定要加載的靜態(tài)資源。
5.第三方中間件
形如之前我們的body-parser,采用引入外部模塊的方式來獲得