引入:前后端分離:( 前端:寫頁面;請求數據;數據處理;后端:寫 api 接口)
補充:學完 express,可以看koa 這個框架。
實現:登陸接口
express入門
1、安裝express, 引入第三方框架
npm install express --save
⚠️ 第三方模塊引用加載規范(首先在當前目錄的node_modules 依次向上尋找)。
2、代碼部分
const express =require('express') const app=express() // express 實例化
const bodypaser=require('body-parser') // app.use 使用中間件(插件) // 解析表單數據 x-www-form-urlencode app.use(bodypaser.urlencoded({ extended: false })) app.use(bodypaser.json())
get接口
app.get('/user/login',(req,res)=>{ // 最簡單的api 接口 // 接受get 參數 :通過 req.query 接收 console.log(req.query) console.log('你好') let {us,ps}=req.query // 處理數據 if(us==='wangyi'&&ps==456){ res.send({err:0,msg:'login ok'}) }else{ res.send({err:-1,msg:'us pass no ok'}) } })
post接口
app.post('/user/reg',(req,res)=>{ // 接受post 數據 :消息體 請求體 通過req.body接收 let {us,ps}=req.body console.log(req.body) // express 不能直接解析消息體,需要第三方插件body-parser. // 通過第三方的插件實現解析 if(us==123&&ps==123){ res.send({err:0,msg:'ok'}) }else{ res.send({err:-1,msg:'nook'}) }
app.listen(3000,()=>{ // 監聽3000 端口 開啟服務器 console.log('server start') })
express路由:
https://expressjs.com/en/guide/routing.html
express-midelware 中間件:
共三種類型:1、內置中間件 static;2、自定義中間件,分局部和全局;3、第三方中間件(如body-parser)(攔截器)
作用:減少重復代碼,可以理解為攔截器,中間件的內容,優先執行處理,切記一定要next(), 否則終止。
自定義中間件(全局)示例👇
自定義中間件(局部)示例👇
靜態資源目錄
指定一個目錄 目錄可以被訪問 如,apache 下的(wwww路徑)
提供資源的絕對路徑
需用到:node內置模塊: path 路徑模塊
實現絕對路徑和相對路徑的拼接:
const express=require('express') const path=require('path') const app=express() // console.log(__dirname) // console.log(path.join(__dirname,'./hehe')) // app.use(express.static(path.join(__dirname,'./hehe'))) // 域名:3000, 直接指向,拼接后的靜態目錄,localhost:3000/hehe/... app.use('/public',express.static(path.join(__dirname,'./hehe'))) // localhost:3000/public/hehe/... app.listen(3000,()=>{ console.log('server start') })
服務器相關總結:
服務器:1.就是一台電腦 2.還需要服務器軟件(apach tomcat iis nginx node) 3.服務器ip 和端口號:一個程序占用一個端口號
局域網:也叫內網,服務器通過網線(或者無線)連接,每個電腦都會有一個IP。比如 學校,公司
外網:(國內的網整個來看也是個局域網)
ip: 確定服務器主機的位置
端口號:確定服務器中某一個程序
api 接口的構成要素:
ip, port, pathname ,
method: get post
接受用戶傳遞的數據
模擬post請求: postman工具
接收參數👇
接受get 參數 :通過 req.query 接收
接受post 數據 :消息體 請求體 通過req.body接收,
-
⚠️ 通過express 不能直接解析消息體,需要第三方 body-parser 插件進行解析
接收post請求參數的幾種數據格式 : json x-www-form-urencode formdata ,注意:前后端數據要統一。