日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

react中的axios模塊你了解嗎_React

作者:Han_Zhou_Z ? 更新時間: 2022-05-14 編程語言

一、react中axios模塊的使用

1、基于Promise的HTTP庫用在瀏覽器和node.js中

可以提供以下服務:

(1)從瀏覽器中創建XMLHttpRequest

(2)從node.js創建http請求

(3)支持PromiseAPI

(4)攔截請求和響應

(5)轉換請求數據和響應數據

(6)取消請求

(7)自動轉換JSON數據

(8)客戶端支持防御XSRF

2、創建XMLHttpRequest對象:

該對象是ajax(異步請求)的核心

3、在react中安裝axios

npm install axios

4、發起不帶參數的get請求

方式一:axios({ methods: 'get', url: '/ulr' }).then(res => {//請求成功后的處理
            console.log(res)
}).catch(err => {//請求失敗后的處理
           console.error(err);
})

'res'是服務器返回的響應數據

err是請求失敗后的信息

方式二:axios.get('/url').then(res => {
            console.log(res)
}).catch(err => {
           console.error(err);
})

5、帶參數的get請求

在服務器端獲取請求參數的方式--> req(request).query.參數名

方式一: axios.get('/url', {params: {id: 12}}).then(res => {
              console.log(res)
}).catch(err => {
              console.error(err);
})
//請求的地址實際為:http://localhost:8080/url?id=12
方式二:axios({
               methods: 'get',
               url: 'url',
                params: {
                     id:12    //'id'為參數名
                   }
            }).then(res => {
                   console.log(res)
}).catch(err => {
                   console.error(err);
})

6、post請求:發送表單數據和文件上傳

(1)不帶參數的post請求

方法一:axios({
        	method:'post',
	        url:'/url'
        }).then(res=>{})
          .catch(err=>{})
方法二:axios.post('url')
		    .then(res=>{})
			.catch(err=>{})

(2)帶參數的post請求:在服務器端獲取請求參數的方式-->req.body.參數名

服務器端使用req.body.參數名 獲取數據
let data = {}
let config = {}
方式一:  axios.post('/url',{id:12}).then(res => {
                   console.log(res)
            }).catch(err => {
                   console.error(err);
            })
方式二:  axios({
              methods: 'post',
              url: '/url',
              data: {id:12}
          }).then(res => {
                console.log(res)
          }).catch(err => {
                console.error(err);
          })

7、put請求

和post請求類似

8、delete請求

(1)可以像get請求一樣包裝請求參數:在服務器端獲取請求參數的方式--req.query.參數名

參數在url的params中:服務器端使用req.query.參數名 獲取數據
axios.delete('/url', {
params: {id: 12}  //'id'為參數名
}).then(res => {
                console.log(res)
}).catch(err => {
                console.error(err);
})

(2)可以像post請求一樣包裝請求參數:在服務器端獲取請求參數的方式--req.body.參數名

參數在請求體(post)中 將params改為 data就行:服務器端使用req.body.參數名 獲取數據
axios.delete('/url', {
data: {id: 12}  //'id'為參數名
}).then(res => {
                console.log(res)
}).catch(err => {
                console.error(err);
})

強調:axios的響應結構

后臺res.json(result) ? //發送了json格式的數據

相當于{ data: result }

前端res.data

例如:

后臺:

res.json({
    code:1001,
    msg: '小森'
})

?前端:

res.data.code

res.data.msg

總結

原文鏈接:https://blog.csdn.net/Han_Zhou_Z/article/details/123345319

欄目分類
最近更新