成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

進階全棧的第一步:能實現這五種接口

開發
如果你想成為一名全棧工程師,那么不能滿足于會寫這幾種方式的前端代碼,后端代碼也得會寫。所以,這篇文章我們來實現下前后端代碼,把整個鏈路打通,真正掌握它們。

上一篇文章我們總結了網頁開發的 5 種 http/https 傳輸數據的方式:

  • url param
  • query
  • form urlencoded
  • form data
  • json

這 5 種方式覆蓋了開發中絕大多數場景,掌握好這些就能輕松應對各種 http/https 數據通信的需求。

如果你想成為一名全棧工程師,那么不能滿足于會寫這幾種方式的前端代碼,后端代碼也得會寫。

所以,這篇文章我們來實現下前后端代碼,把整個鏈路打通,真正掌握它們。

前端使用 axios 發送請求,后端使用 Nest.js 作為服務端框架。

準備工作

首先我們要把 Nest.js 服務端跑起來,并且支持 api 接口、靜態頁面。

Nest.js 創建一個 crud 服務是非常快的,只需要這么幾步:

  • 安裝 @nest/cli,使用 nest new xxx 創建一個 Nest.js 的項目,
  • 在根目錄執行 nest g resource person 快速生成 person 模塊的 crud 代碼
  • npm run start 啟動 Nest.js 服務

這樣一個有 person 的 crud 接口的服務就跑起來了,是不是非常快。

服務跑起來以后是這樣的

打印出了有哪些接口可以用,可以在 postman 或者瀏覽器來測試下:

api 接口跑通了,再支持下靜態資源的訪問:

main.ts 是負責啟動 Nest.js 的 ioc 容器的,在腳手架生成的代碼的基礎上,調用下 useStaticAssets 就可以支持靜態資源的請求。

  1. async function bootstrap() { 
  2.   const app = await NestFactory.create<NestExpressApplication>(AppModule); 
  3.   app.useStaticAssets(join(__dirname, '..''public'), { prefix: '/static'}); 
  4.   await app.listen(3000); 
  5. bootstrap(); 

我們指定 prefix 為 static,然后再靜態文件目錄 public 下添加一個 html:

  1. <html> 
  2. <body>hello</body> 
  3. </html> 

重啟服務,然后瀏覽器訪問下試試:

api 接口和靜態資源的訪問都支持了,接下來就分別實現下 5 種前后端 http 數據傳輸的方式吧。

url param

url param 是 url 中的參數,Nest.js 里通過 :參數名 的方式來聲明,然后通過 @Param(參數名) 的裝飾器取出來注入到 controller:

  1. @Controller('api/person'
  2. export class PersonController { 
  3.   @Get(':id'
  4.   urlParm(@Param('id') id: string) { 
  5.     return `received: id=${id}`; 
  6.   } 

前端代碼就是一個 get 方法,參數放在 url 里:

  1. <!DOCTYPE html> 
  2. <html lang="en"
  3. <head> 
  4.     <script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script> 
  5. </head> 
  6. <body> 
  7.     <script> 
  8.         async function urlParam() { 
  9.             const res = await axios.get('/api/person/1'); 
  10.             console.log(res);             
  11.         } 
  12.         urlParam(); 
  13.    </script> 
  14. </body> 

啟動服務,在瀏覽器訪問下:

控制臺打印了服務端返回的消息,證明服務端拿到了通過 url param 傳遞的數據。

通過 url 傳遞數據的方式除了 url param 還有 query:

query

query 是 url 中 ? 后的字符串,需要做 url encode。

在 Nest.js 里,通過 @Query 裝飾器來取:

  1. @Controller('api/person'
  2. export class PersonController { 
  3.   @Get('find'
  4.   query(@Query('name'name: string, @Query('age') age: number) { 
  5.     return `received: name=${name},age=${age}`; 
  6.   } 

前端代碼同樣是通過 axios 發送一個 get 請求:

  1. <!DOCTYPE html> 
  2. <html lang="en"
  3. <head> 
  4.     <script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script> 
  5. </head> 
  6. <body> 
  7.     <script> 
  8.         async function query() { 
  9.             const res = await axios.get('/api/person/find', { 
  10.                 params: { 
  11.                     name'光'
  12.                     age: 20 
  13.                 } 
  14.             }); 
  15.             console.log(res);             
  16.         } 
  17.         query(); 
  18.    </script> 
  19. </body> 
  20. </html> 

參數通過 params 指定,axios 會做 url encode,不需要自己做。

然后測試下:

服務端成功接受了我們通過 query 傳遞的數據。

上面兩種(url param、query)是通過 url 傳遞數據的方式,下面 3 種是通過 body 傳遞數據。

html urlencoded

html urlencoded 是通過 body 傳輸數據,其實是把 query 字符串放在了 body 里,所以需要做 url encode:

用 Nest.js 接收的話,使用 @Body 裝飾器,Nest.js 會解析請求體,然后注入到 dto 中。

dto 是 data transfer object,就是用于封裝傳輸的數據的對象:

  1. export class CreatePersonDto { 
  2.     name: string; 
  3.     age: number; 
  1. import { CreatePersonDto } from './dto/create-person.dto'
  2.  
  3. @Controller('api/person'
  4. export class PersonController { 
  5.   @Post() 
  6.   body(@Body() createPersonDto: CreatePersonDto) { 
  7.     return `received: ${JSON.stringify(createPersonDto)}` 
  8.   } 

前端代碼使用 post 方式請求,指定 content type 為 application/x-www-form-urlencoded,用 qs 做下 url encode:

  1. <!DOCTYPE html> 
  2. <html lang="en"
  3. <head> 
  4.     <script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script> 
  5.     <script src="https://unpkg.com/qs@6.10.2/dist/qs.js"></script> 
  6. </head> 
  7. <body> 
  8.     <script> 
  9.         async function formUrlEncoded() { 
  10.             const res = await axios.post('/api/person', Qs.stringify({ 
  11.                 name'光'
  12.                 age: 20 
  13.             }), { 
  14.                 headers: { 'content-type''application/x-www-form-urlencoded' } 
  15.             }); 
  16.             console.log(res);   
  17.         } 
  18.  
  19.         formUrlEncoded(); 
  20.     </script> 
  21. </body> 
  22. </html> 

測試下:

服務端成功的接收到了數據。

其實比起 form urlencoded,使用 json 來傳輸更常用一些:

json

json 需要指定 content-type 為 application/json,內容會以 JSON 的方式傳輸:

后端代碼同樣使用 @Body 來接收,不需要做啥變動。form urlencoded 和 json 都是從 body 取值,Nest.js 內部會根據 content type 做區分,使用不同的解析方式。

  1. @Controller('api/person'
  2. export class PersonController { 
  3.   @Post() 
  4.   body(@Body() createPersonDto: CreatePersonDto) { 
  5.     return `received: ${JSON.stringify(createPersonDto)}` 
  6.   } 

前端代碼使用 axios 發送 post 請求,默認傳輸 json 就會指定 content type 為 application/json,不需要手動指定:

  1. <!DOCTYPE html> 
  2. <html lang="en"
  3. <head> 
  4.     <script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script> 
  5. </head> 
  6. <body> 
  7.     <script> 
  8.         async function json() { 
  9.             const res = await axios.post('/api/person', { 
  10.                 name'光'
  11.                 age: 20 
  12.             }); 
  13.             console.log(res);      
  14.         } 
  15.         json(); 
  16.     </script> 
  17. </body> 
  18. </html> 

測試下:

服務端成功接收到了通過 json 傳遞的數據。

json 和 form urlencoded 都不適合傳遞文件,想傳輸文件要用 form data:

form data

form data 是用 -------- 作為 boundary 分隔傳輸的內容的:

Nest.js 解析 form data 使用 FilesInterceptor 的攔截器,用 @UseInterceptors 裝飾器啟用,然后通過 @UploadedFiles 來取。非文件的內容,同樣是通過 @Body 來取。

  1. import { AnyFilesInterceptor } from '@nestjs/platform-express'
  2. import { CreatePersonDto } from './dto/create-person.dto'
  3.  
  4. @Controller('api/person'
  5. export class PersonController { 
  6.   @Post('file'
  7.   @UseInterceptors(AnyFilesInterceptor()) 
  8.   body2(@Body() createPersonDto: CreatePersonDto, @UploadedFiles() files: Array<Express.Multer.File>) { 
  9.     console.log(files); 
  10.     return `received: ${JSON.stringify(createPersonDto)}` 
  11.   } 

前端代碼使用 axios 發送 post 請求,指定 content type 為 multipart/form-data:

  1. <!DOCTYPE html> 
  2. <html lang="en"
  3. <head> 
  4.     <script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script> 
  5. </head> 
  6. <body> 
  7.     <input id="fileInput" type="file" multiple/> 
  8.     <script> 
  9.         const fileInput = document.querySelector('#fileInput'); 
  10.  
  11.         async function formData() { 
  12.             const data = new FormData(); 
  13.             data.set('name','光'); 
  14.             data.set('age', 20); 
  15.             data.set('file1', fileInput.files[0]); 
  16.             data.set('file2', fileInput.files[1]); 
  17.  
  18.             const res = await axios.post('/api/person/file', data, { 
  19.                 headers: { 'content-type''multipart/form-data' } 
  20.             }); 
  21.             console.log(res);      
  22.         } 
  23.  
  24.          
  25.         fileInput.onchange = formData; 
  26.     </script> 
  27. </body> 
  28. </html> 

file input 指定 multiple 可以選擇多個文件。

測試下:

服務端接收到了 name 和 age:

去服務器控制臺看下:

可以看到,服務器成功的接收到了我們上傳的文件。

全部代碼上傳到了 github:https://github.com/QuarkGluonPlasma/nestjs-exercize

總結

我們用 axios 發送請求,使用 Nest.js 起后端服務,實現了 5 種 http/https 的數據傳輸方式:

其中前兩種是 url 中的:

url param:url 中的參數,Nest.js 中使用 @Param 來取

query:url 中 ? 后的字符串,Nest.js 中使用 @Query 來取

后三種是 body 中的:

form urlencoded:類似 query 字符串,只不過是放在 body 中。Nest.js 中使用 @Body 來取,axios 中需要指定 content type 為 application/x-www-form-urlencoded,并且對數據用 qs 做 url encode

json:json 格式的數據。Nest.js 中使用 @Body 來取,axios 中不需要單獨指定 content type,axios 內部會處理。

form data:通過 ----- 作為 boundary 分隔的數據。主要用于傳輸文件,Nest.js 中要使用 FilesInterceptor 來處理,用 @UseInterceptors 來啟用。其余部分用 @Body 來取。axios 中需要指定 content type 為 multipart/form-data,并且用 FormData 對象來封裝傳輸的內容。

這 5 種 http/https 的傳輸數據的方式覆蓋了絕大多數開發場景,如果你想進階全棧,能夠提供這 5 種接口是首先要做到的。

 

責任編輯:武曉燕 來源: 神光的編程秘籍
相關推薦

2021-01-15 18:17:06

網絡協議分層

2011-07-25 14:17:46

BSMIT運維北塔

2015-06-02 11:42:00

Cloud FoundAzure

2019-11-20 10:54:46

無密碼身份驗證網絡安全

2009-01-18 08:49:04

Java入門JDK

2013-01-15 09:17:11

2012-07-11 16:43:14

飛視美

2010-07-01 13:44:12

2020-07-22 22:10:34

互聯網物聯網IOT

2012-08-30 11:14:11

云計算虛擬化

2018-02-10 11:24:39

Python數據程序

2021-08-24 05:07:25

React

2020-11-17 14:55:36

亞馬遜云科技遷移

2024-02-26 10:08:01

2020-11-11 07:09:05

隔離直播系統

2017-09-19 09:36:55

思科服務

2010-11-05 10:32:50

云應用程序規劃

2013-04-03 09:22:14

虛擬化網絡虛擬化

2010-01-21 10:29:54

java認證

2023-06-13 13:51:00

云遷移云平臺業務
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 中文字幕人成乱码在线观看 | 欧洲精品在线观看 | 色精品视频 | 欧美日韩a | 伊人久麻豆社区 | 一本岛道一二三不卡区 | 色必久久| 嫩草视频免费 | 在线视频一区二区三区 | 国产女人叫床高潮大片免费 | 日韩一区二区三区视频 | 国产欧美一区二区三区久久人妖 | 91精品国产综合久久婷婷香蕉 | 国产精品一区2区 | 在线成人免费观看 | 91精品国产91久久久久久吃药 | 日本视频免费观看 | 午夜视频一区二区 | 精品久久电影 | 狠狠夜夜 | 亚洲精品免费观看 | 国产一区二区三区在线看 | 亚洲午夜视频在线观看 | 久久精品国产v日韩v亚洲 | 亚洲欧美日韩精品久久亚洲区 | 日韩中出 | 成年人视频在线免费观看 | 欧美中文字幕一区二区三区亚洲 | 日日干日日射 | 日韩一区二区在线观看视频 | 操久久| 久久久久久免费精品一区二区三区 | 国产视频久久久 | 国产区精品视频 | 久久爱综合 | 欧美5区 | 欧美色性 | 久久久精品视频免费看 | 国产精品美女www爽爽爽视频 | 日日夜夜影院 | 久久国 |