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