express系列一:experss基礎搭建及使用

experss​

express有利於快速搭建一個項目。做了很多做了很多各種各樣的封裝,省去很多麻煩。(比如:後端接受post參數需要用到中間件)

API 使用您所選擇的各種 HTTP 實用工具和中間件,快速方便地創建強大的 API。

安裝使用

1、安裝

//初始化
D:\phpStudy\PHPTutorial\WWW\AAAThree\btest\day03\express>`npm init -y`
  • Wrote to D:\phpStudy\PHPTutorial\WWW\AAAThree\btest\day03\express\package.json:
    
    {
      "name": "express",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }
    

2、使用

​ 打開express官網[ http://www.expressjs.com.cn/ ] 快速入門,hellow world 複製例子使用

//引入依賴
const express = require('express')
////獲取express實例並且創建服務器
const app = express()

/*使用中簡件
*/
//當用戶訪問根路徑的時候返回給用戶一個文本 ,類似一個路由
app.get('/', (req, res) => res.send('Hello World!'))
//綁定端口號
app.listen(3000, () => console.log('Example app listening on port 3000!'))

3、運行

在終端中運行node index,開啓了一個服務器。

PS D:\phpStudy\PHPTutorial\WWW\AAAThree\btest\day03\express> node index
Example app listening on port 3000!

打開 http://localhost:3000/ 。會顯示 Hello World!
如果打開一個不存在的頁面http://localhost:3000/list,它也不會一直轉,會找一個不存在的頁面返回Cannot GET /list

比較express與http請求的區別

express比較簡單,可以簡單寫路由,提供中間件.在express中的封裝讀取文件的功能全被做好了,express簡化了http模塊

案例

修改index.js中代碼,新建public文件夾中新建index.html,

//引入依賴
const express = require('express')
////獲取設定app是express實例並且創建服務器
const app = express();
const path = require("path");
app.use(express.static(path.join(__dirname, "./public")))
//express.static(path.join(__dirname, "./public"))理解爲中間件

//綁定端口號
app.listen(3000, () => console.log('Example app listening on port 3000!'))

將package.json文件中修改爲自動監聽


  "scripts": {
    "dev": "supervisor index.js"
}

啓動瀏覽器[http://localhost:3000/] 會出現一個index.html,還可以寫js和css

app是express實例 ,在index.js中創建
express接口文檔中 學習app對象的方法

app.set設定 檢索設置的值

app.set('views', path.join(__dirname, 'views'));//指定模板文件的路徑
app.set('view engine', 'ejs');//當前模板使用的是ejs模板

app.use使用中間件

app.use:使用中間件
    參數1:路徑    選填
    參數2: 中間件  (函數)

    req request
    res response
    next 執行下一個中間件
    
    中間件:
    1、內置中間件
    2、自定義中間件
    3、第三方中間件
    4、路由中間件
    5、報錯中間件
    .....
    
    什麼是中間件
        請求和回覆之間的一個應用

1、內置中間件

const express = require('express')
const app = express();
const path = require("path");
//使用中間件  設置靜態文件的路徑及訪問  內置中間件
app.use(express.static(path.join(__dirname, "./public")))

2、自定義中間件

在public文件夾中建立list.html,order.html

const express = require('express')
const app = express();
const path = require("path");
const fs = require("fs")
//自定義中間件
//next 執行下一個中間件
app.use((req,res,next)=>{
    if(req.url == "/"){
       res.end("index")
    }else{
        next();
    }
})

app.use((req,res,next)=>{
    if(req.url == "/list"){
        res.end("list")
    }else{
        next()
    }
})

app.use((req,res,next)=>{
    if(req.url == "/order"){
        res.end("order")
    }
})
//綁定端口號
app.listen(3000, () => console.log('Example app listening on port 3000!'))

3、第三方中間件

在express官網上的資源中有一箇中間件是可供使用的第三方中間件

選用body-parser中間件,在express文件中安裝中間件,安裝完引用

//安裝
$ npm install body-parser
//引用
const bodyParser = require('body-parser')
//使用中間件,需要先使用內置中間件
app.use(express.static(path.join(__dirname, "./public")))
app.use(bodyParse.urlencoded({ extended: false }))//urlencoded做解析

第三方中間件代碼,需要打開內置中間件

const express = require('express')
const app = express();
const path = require("path");
const fs = require("fs")
const bodyParse = require("body-parser");
//使用中間件  設置靜態文件的路徑及訪問  內置中間件
app.use(express.static(path.join(__dirname, "./public")))
app.use(bodyParse.urlencoded({ extended: false }))

//第三方中間件
app.post("/list", (req, res) => {
    // console.log(req.body);//先測試是否能接受到數據,然後在返回數據
    let { username, age } = req.body;
    res.json({//expres提供的好的返回信息的方法,只有express中有
        username,
        age
    })
})

app.listen(3000, () => console.log('Example app listening on port 3000!'))

在index.html中添加script代碼

POST請求接受數據
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.js"></script>
<script>
    $.ajax({
        type:"post",
        url:"/list",
        data:{
            username:"ALLALL",
            age:20
        },
        success:(data)=>{
            console.log(data);
        }
    })
 </script>

tips: cdn 託管網站 BootCDN [https://www.bootcdn.cn/ ]

在瀏覽器中刷新,可以得到Network中的list 顯示200請求成功

//點擊list發現Preview中會有返回值    如果list是pendding狀態可以重啓服務器
{username: "ALLALL", age: "20"}
age: "20"
username: "ALLALL"
GET請求接受數據
<!--//修改html中的代碼請求方式爲get請求-->
<script>
    $.ajax({
        type:"get",
        url:"/user",
        data:{
            username:"ALLALL",
            age:20
        },
        success:(data)=>{
            console.log(data);
        }
    })
 </script>
//index.js中代碼
const express = require('express')
const app = express();
const path = require("path");
const fs = require("fs")
const bodyParse = require("body-parser");
//使用中間件  設置靜態文件的路徑及訪問  內置中間件
app.use(express.static(path.join(__dirname, "./public")))
app.use(bodyParse.urlencoded({ extended: false }))

//第三方中間件
app.get("/user", (req, res) => {
    // console.log(req.query);//先測試是否能接受到數據,然後在返回數據
    let { username, age } = req.query;
    res.json({//expres提供的好的返回信息的方法,只有express中有
        username,
        age
    })
})

app.listen(3000, () => console.log('Example app listening on port 3000!'))

在瀏覽器中刷新,可以得到Network中的user?username=ALLALL&age=20 顯示304請求成功

//點擊user?username=ALLALL&age=20
//發現Preview中會有返回值  如果是pendding狀態可以重啓服務器
{username: "ALLALL", age: "20"}
age: "20"
username: "ALLALL"

4、路由中間件

路由中間件 必須放在實例之後,便於維護,寫哪個接口就去訪問哪個文件夾

//當用戶訪問"/user",走userRouter路由
app.use("/user",userRouter)
//所以要在上面定義一個userRouter
const userRouter = require("./router")

新建一個router文件夾新建一個index.js文件,並修改express中index.js文件夾的代碼

const userRouter = require("./router")
//修改爲
const userRouter = require("./router/index")

編寫router文件夾中的index.js文件,/user下的文件接口都是和用戶有關,存放的是用戶的登錄註冊信息,重做get 和post請求

const express = require("express");//引入模塊
//const router = express.Router()獲取路由實例
const router = express.Router();

//中間件,  next用到就寫,用不到可以不寫
router.get("/register",(req,res,next)=>{
    let {username,age} = req.query;

    res.json({
        username,
        age
    })
})

router.post("/login",(req,res,next)=>{
    let {username,age} = req.body;

    res.json({
        username,
        age
    })
})

//用到需要導出
module.exports = router
先寫get 註冊

修改public中index.html中script

$.ajax({
    type:"get",
    url:"/user/register",
    data:{
        username:"ALLALL",
        age:20
    },
    success:(data)=>{
        console.log(data);
    }
})

然後編寫router中的index

const express = require("express");
const router = express.Router();

router.get("/register",(req,res,next)=>{
    let {username,age} = req.query;

    res.json({
        username,
        age
    })
})
module.exports = router

編寫express中的index.js

const app = express();
const path = require("path");
const fs = require("fs");//引入文件模塊,方便自定義中間件用
const bodyParse = require("body-parser");
//路由中間件,路由下邊可以連接不同的文件夾找到不同的接口
const userRouter = require("./router/index");

//使用中間件  設置靜態文件的路徑及訪問  內置中間件
app.use(express.static(path.join(__dirname, "./public")))
app.use(bodyParse.urlencoded({ extended: false }));
app.use("/user",userRouter)

//get請求  註冊
app.get("/user/register", (req, res) => {
    let { username, age } = req.query;//內置中間件,直接請求
    // console.log({ username, age })
    res.json({
        username,
        age
    })
})

//監聽端口號
app.listen(3000, () => console.log('Example app listening on port 3000!'))
再寫post 登錄

修改public中index.html中script

$.ajax({
    type:"post",
    //屬於用戶下邊的接口所以走用戶的路徑
    url:"/user/login",
    data:{
        username:"ALLALL",
        age:20
    },
    success:(data)=>{
        console.log(data);
    }
})

然後寫router中的index.js

const express = require("express");
const router = express.Router();

router.post("/login",(req,res,next)=>{
   	//post請求用body
    let {username,age} = req.body;

    res.json({
        username,
        age
    })
})
module.exports = router

重寫express中的index.js

const app = express();
const path = require("path");
const fs = require("fs");//引入文件模塊,方便自定義中間件用
const bodyParse = require("body-parser");
//路由中間件,路由下邊可以連接不同的文件夾找到不同的接口
const userRouter = require("./router/index");

//使用中間件  設置靜態文件的路徑及訪問  內置中間件
app.use(express.static(path.join(__dirname, "./public")))
app.use(bodyParse.urlencoded({ extended: false }));
app.use("/user",userRouter)

//get請求  註冊
app.get("/user/register", (req, res) => {
    let { username, age } = req.query;//內置中間件,直接請求
    // console.log({ username, age })
    res.json({
        username,
        age
    })
})

//監聽端口號
app.listen(3000, () => console.log('Example app listening on port 3000!'))

報錯信息

GET http://localhost:3000/user/register?username=ALLALL&age=20 404 (Not Found)

報404錯誤,原因是後端express/index.js中沒有引入const userRouter = require("./router/index");

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章