如何搭建一個簡單的本地服務: 搭一個本地服務器
首先創建倆個點擊事件
一個post請求和get請求,然后改變點擊事件的this指向
在構造函數 constructor 中 改變,
點擊查看 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請求結果:
服務端: