react fetch方法 get/post 请求数据使用和跨域代理

get请求

  定义在	componentDidMount声明周期函数中
 
  componentDidMount(){
      //userData 请求的地址
      fetch('/userData').then(req=>req.json())
      .then(data=>{
         console.log(data) //请求到的数据
     })
   }

post请求需要传参和设置头请求

  定义在一个onClick事件里
   
    getData=()=>{
        fetch('/userData',{
            method:"post",
            headers:{
               "Content-Type":"application/json"
                },
            body:JSON.stringify({//请求的参数
                   user:'zhang666',
                   age:21,
               }) 
         }).then(res=>res.json()).then(data=>{
                     console.log(data) //请求的结果
             })
      }
  

  render(){
         <div>
              <button onClick={this.getData}>post请求</button>
        </div>
    }

跨域代理设置


在package.json文件中设置

{
  "name": "shenghuoyijia",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:9999/"
}

添加 “proxy”: "http://localhost:9999/"这行代码
注:http://localhost:9999/ 为请求的端口号。请求的完整地址实际是http://localhost:9999/userData

但是由于浏览器同源策略的关系(浏览器认为所有的跨域请求都是不安全的所以会阻止)

  fetch('http://localhost:9999/userData').then(req=>req.json())
      .then(data=>{
         console.log(data) /
     })
     跨域请求浏览器默认阻止会 请求失败报错

通过设置跨域代理

 "proxy": "http://localhost:9999/"
 
 fetch('/userData').then(req=>req.json())
      .then(data=>{
         console.log(data) 
     })
     请求地址userData浏览器认为没有跨域 请求成功

所以需要通过设置跨域代理

发布了14 篇原创文章 · 获赞 23 · 访问量 1906

猜你喜欢

转载自blog.csdn.net/weixin_43835425/article/details/102926613