失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > get请求中传json参数报400的错误_react的数据请求

get请求中传json参数报400的错误_react的数据请求

时间:2023-04-15 07:37:41

相关推荐

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))展示返回错误提示

结果

服务端:

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

服务端:

如果觉得《get请求中传json参数报400的错误_react的数据请求》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。