Nest.js中使用HTTP五種數(shù)據(jù)傳輸方式小結(jié)
前言
Nest.js作為JS的后端框架,是JS開發(fā)者邁向全棧的不錯選擇,Nest.js也是企業(yè)中最流行的Node框架,它提供了IOC、AOP、微服務(wù)等架構(gòu)特性。
接下來就讓我們認(rèn)識一下Nest.js在HTTP五種數(shù)據(jù)傳輸方式中的使用。
Param
param 傳輸方式是通過url的參數(shù)傳遞,也是最常見的一種前端向后端傳遞參數(shù)的方式。
如果Nest后端接口這樣設(shè)置
@Controller('api/parma')
export class ParmaController {
@Get(':id')
urlParm(@Param('id') id: string) {
return `id=${id}`;
}
}前端請求這樣請求
axios.get("http://localhost:3000/1in/parma/cdut")那么,其中的cdut會被當(dāng)做parma參數(shù)被Nest截取,Nest也為我們提供了便捷的@Param裝飾器,使我們可以更便捷的提取param參數(shù)。
Query
query傳輸方式也是通過url的參數(shù)傳遞,但是他與parma略有不同。query傳輸方式需要做url encode
如果Nest后端接口這樣設(shè)置
@Controller('api/query')
export class QueryController {
@Get('find') query(@Query('name') name: string, @Query('age') age: number)
{ return `name=${name},age=${age}`; } }前端請求這樣請求
axios.get("http://localhost:3000/1in/query/",{
name:"1in",
age:20
})因?yàn)閍xios會自動幫我們url encode,所以我們不需要自己手動url encode,在Nest中,我們通過@Query這個裝飾器來取到query參數(shù)。
Form urlencoded
與query不同的是,from urlencoded是通過post請求中的body來傳遞參數(shù),實(shí)際上,就是把query的參數(shù)放在body中。
需要注意的是我們需要在請求頭中設(shè)置'content-type': 'application/x-www-form-urlencoded'。
如果Nest后端接口這樣設(shè)置
@Controller('api/form-urlencoded')
export class FormUrlencodedController {
@Post() body(@Body() body)
{ return `${JSON.stringify(body)}` }
}前端請求前,我們需要使用qs這個庫來做一下url encode
前端請求這樣請求
axios.post('http://localhost:3000/api/form-urlencoded',
Qs.stringify({ name: '1in', age: 20 }),
{ headers: { 'content-type': 'application/x-www-form-urlencoded' } });在Nest中,我們可以通過@Body這個裝飾器來直接取到body中的內(nèi)容。
Json
與form urlencoded不同的是,json需要指定的content-type為application/json,也不需要url encode,同樣的也是通過post請求中的Body傳輸數(shù)據(jù)。
如果Nest后端接口這樣設(shè)置
@Controller('api/json')
export class JsonController {
@Post()
body(@Body() body) {
return `received: ${JSON.stringify(createPersonDto)}`
}
}前端這樣請求
axios.post("http://localhost:3000/api/json",{
name:"1in",
age:20
})因?yàn)閍xios會幫我們設(shè)置content-type為application/json,所以不需要我們自動設(shè)置,Nest同樣也是通過@Body裝飾器取到body中傳輸?shù)臄?shù)據(jù)。
Form data
form data是通過---------作為boundary傳輸?shù)膬?nèi)容,主要用于傳輸文件。
如果Nest后端接口這樣設(shè)置
import { AnyFilesInterceptor } from '@nestjs/platform-express';
@Controller('api/form-data')
export class FormDataController {
@Post('file')
@UseInterceptors(AnyFilesInterceptor())
body2(@Body() body, @UploadedFiles() files: Array<Express.Multer.File>) {
console.log(files);
return `received: ${JSON.stringify(body)}`
}
}前端代碼使用 axios 發(fā)送 post 請求,指定 content type 為 multipart/form-data
前端請求是這樣的
<!DOCTYPE html>
<html lang="en">
<head>
? ? <script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script>
</head>
<body>
? ? <input id="updateFile" type="file" multiple/>
? ? <script>
? ? ? ? const fileInput = document.querySelector('#updateFile');
? ? ? ? async function formData() {
? ? ? ? ? ? const data = new FormData();
? ? ? ? ? ? data.set('name','1in');
? ? ? ? ? ? data.set('age', 20);
? ? ? ? ? ? data.set('file1', fileInput.files[0]);
? ? ? ? ? ? data.set('file2', fileInput.files[1]);
? ? ? ? ? ? const res = await axios.post('http://localhost:3000/api/form-data/file', data, {
? ? ? ? ? ? ? ? headers: { 'content-type': 'multipart/form-data' }
? ? ? ? ? ? });
? ? ? ? }
? ? ? ? fileInput.onchange = formData;
? ? </script>
</body>
</html>form data通過 ----- 作為 boundary 分隔的數(shù)據(jù)。主要用于傳輸文件,在Nest中使用 FilesInterceptor 來處理其中的 binary 字段,用 @UseInterceptors 裝飾器來啟用,其余字段用 @Body 裝飾器來取。axios 發(fā)送請求時(shí),需要設(shè)置請求頭,指定 content type為 multipart/form-data,并且用 FormData 對象來封裝傳輸?shù)膬?nèi)容。
到此這篇關(guān)于Nest.js中使用HTTP五種數(shù)據(jù)傳輸方式小結(jié)的文章就介紹到這了,更多相關(guān)Nest.js HTTP數(shù)據(jù)傳輸內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解基于Koa2開發(fā)微信二維碼掃碼支付相關(guān)流程
這篇文章主要介紹了詳解基于Koa2開發(fā)微信二維碼掃碼支付相關(guān)流程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
npm?install安裝報(bào)錯:gyp?info?it?worked?if?it?ends?with?
今天新啟動一個項(xiàng)目,在 npm install 安裝依賴項(xiàng)時(shí)出現(xiàn)報(bào)錯,所以下面這篇文章主要給大家介紹了關(guān)于npm?install安裝報(bào)錯:gyp?info?it?worked?if?it?ends?with?ok的解決方法,需要的朋友可以參考下2022-07-07
Node.js API詳解之 Error模塊用法實(shí)例分析
這篇文章主要介紹了Node.js API詳解之 Error模塊用法,結(jié)合實(shí)例形式分析了Node.js API中Error模塊相關(guān)功能、函數(shù)、用法及操作注意事項(xiàng),需要的朋友可以參考下2020-05-05
在Node.js應(yīng)用中讀寫Redis數(shù)據(jù)庫的簡單方法
這篇文章主要介紹了在Node.js應(yīng)用中讀寫Redis數(shù)據(jù)庫的簡單方法,Redis是一個內(nèi)存式高速數(shù)據(jù)庫,需要的朋友可以參考下2015-06-06
node?NPM庫string-random生成隨機(jī)字符串學(xué)習(xí)使用
這篇文章主要為大家介紹了node?NPM庫string-random生成隨機(jī)字符串學(xué)習(xí)使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07

