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请求结果:

 服务端:

猜你喜欢

转载自www.cnblogs.com/wulicute-TS/p/12000748.html