react 元件axios 互動請求筆記

2021-08-14 19:14:57 字數 2422 閱讀 7842

個人建議使用npm安裝開始專案(進入到相關命令列工具中操作即可)

使用npm:

$ npm i axios

tip:

react在引進axios時所用 '' 實際為 `` 即反引號!好處就是不用拼接字串``,遇到變數就是${}就可以了。

示例一

使用乙個get請求

//發起乙個login請求,引數為給定的id

axios.get(

'/login?id=12345')

.then(

function(res))

.catch(

function(error));

//上面的請求也可選擇以下面的方式來改寫

axios.get(

'/user',

}) .then(

function(res))

.catch(

function(error));

下面是我自己在專案裡面常用的寫法,個人覺得不錯,貢獻出來......

例如:let idid=this.props.id

let timestamp = date.parse(new date());

axios.get(`$/invoice/getlistnogroup?id=$&×tamp=$`)

.then(res=>)

.catch(err=>console.log(err))

示例二

發起乙個post請求

axios.post(

'/reg',)

.then(

function(res))

.catch(

function(error));

下面是我自己在專案裡面常用的寫法,個人覺得不錯,貢獻出來......

例如:let data=

axios.post(`$/userinfo/login`,data)

.then(res=>this.loginok(res))

.catch(err=>this.loginerr(err))

示例三

發起乙個多重併發請求

functiongetuser()

functiongetaccount()

axios.all([getuer(),get

account()])

.then(axios.spread(

function(acc,pers)

));

來來來補充下關於驗證伺服器的一些辦法:

來乙個類似原生的:

axios.post("","client_id=client2&client_secret=secret&username="+username+"&password="+password+"&grant_type=password")

.then(res=>)

.catch(err=>)

來乙個axios的    axios.post(`$/connect/token`,`client_id=client2&client_secret=secret&username=$&password=$&grant_type=password`)

.then(res=>)

.catch(err=>)

來乙個formdata形式:

axios.post(`$/user/edit_password`,`userid=$&token=$&oldpwd=$&password=$&passwords=$`)

.then((res)=>)

.catch((err)=>)

來乙個json形式:

let userid=this.props.userid;

let token=this.props.token;

let oldpwd=this.state.oldpassword;

let password=this.state.password;

let passwords=this.state.passwords;

axios.post(`$/user/edit_password`,data)

.then((res)=>)

.catch((err)=>)

IHttpHandler 接收axios請求的引數

前台寫法如下 axios.post apinew goodsapi.ashx?action createcurtain then res error 請求引數格式如下 這個格式的資料一般處理程式用var json context.request formdata 這種寫法獲取不到 所以用下面的方法來...

react 父子元件之間的互動傳值

子元件要呼叫父元件的方法 父元件傳入子元件要調的方法 this.fun.bind this 子元件可通過props直接呼叫 this.props.fun xx 父元件要呼叫子元件的方法 父元件中給子元件設定onref事件,並設定呼叫名 ref this.child ref 子元件中在componen...

react專案axios配置

baseapi.ts import axios,from axios import md5 from js md5 import from antd import cookieutils from utils cookieutils import from types import from con...