get请求中传json参数报400的错误_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))展示返回错误提示
结果

e21d85e60c4c13968bc91340d116ae15.png


服务端:

c52343aa8dfc26f5552a1505ab0c9066.png


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

c5708cf239449b52a64915c115c3cb40.png


服务端:

486ba442b767ea071233fb2a9b033ecc.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值