react的數據請求


如何搭建一個簡單的本地服務:   搭一個本地服務器

首先創建倆個點擊事件

<button onClick={this.getrequest}>get</button>
<button onClick={this.postrequest}>post</button>

一個post請求和get請求,然后改變點擊事件的this指向

在構造函數    constructor   中 改變,

this.getrequest = this.getrequest.bind(this)
this.postrequest = this.postrequest.bind(this)

點擊查看  react中點擊事件為何用bind而不用其他

react中請求方式都需要函數: fatch()

get請求:

getrequest(){
  fetch(
    '/api/get?name=騎上的小摩托&age=20',
    {method:'get'}).then(res=>res.json().then(data=>{console.log(data)})).catch(error=>console.log(error)
}

解釋一下fetch的參數:

第一個參數是請求地址"?"后邊兒是get傳值

第二個參數是mthod:請求方式

.then(res=>res.json()),把返回結果轉換為JSON

.then(data=>{console.log(data)})展示返回數據   /  data是返回的數據(已經轉為json)

.catch(error=>console.log(error))展示返回錯誤提示

結果

 

 

 服務端:

 

 

 

post請求:

postrequest(){
  const obj = {name:'他永遠不會堵車',age:24}   fetch(
    
"/api/post",
    {method:'post',body:JSON.stringify(obj),headers:{'content-type':'application/json'}}).then(res=>res.json()).then(data=>{console.log(data)}).catch(error=>console.log(error))
  )
}

解釋一下fetch的參數:

第一個參數是請求地址

第二個參數是mthod:請求方式

body:JSON.stringify(obj), body傳參,把post的對象轉JSON串, fetch的官方文檔就這么寫的

.then(res=>res.json()), 把返回結果轉換為JSON

.then(data=>{console.log(data)}) 展示返回數據      /  data是返回的數據(已經轉為json)

.catch(error=>console.log(error)) 展示返回錯誤提示

點擊post請求結果:

 

 

 服務端:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM