首页 > 其他分享 >Reactjs学习之fetch请求

Reactjs学习之fetch请求

时间:2023-02-08 11:12:23浏览次数:45  
标签:return 请求 res Reactjs JSON json data fetch

ReactJS通过fecth异步加载数据,并且不需要加载任何模块。是一种XMLHttpRequest的替代方案,除了用ajax获取后台数据外我们还可以使用fetch、axios等方式。

1.GET使用方法:/** reactjs:fetch请求后台 */

fetch("http://localhost:8002/search/" + this.state.name).then(res => {   return res.json()  }).then(data=> {    this.setState({content: data})  }) 说明 1.fetch的返回值是一个promise对象 2.res.json()不是用户需要的数据,通过return返回 3.data才是用户需要的数据   1.POST使用方法 fetch("http://localhost:8002/create/", {         method: 'post',         headers: {             'Content-Type': 'application/json'         },         body: JSON.stringify({        eid: id   }) }).then(res =>{   return res.json();  }).then(data =>{   console.log(data.msg) }).catch(e =>{   console.log(e)  })   说明

1.fetch的返回值是一个promise对象
2.method:HTTP请求方式,默认是GET
   body:请求的参数
   JSON内容是必须的,所以当设置主体时会调用JSON.stringify

标签:return,请求,res,Reactjs,JSON,json,data,fetch
From: https://www.cnblogs.com/michaelShao/p/17100980.html

相关文章