Axios请求

[{
  "id": "1",
  "name": "小红",
  "age": 20,
  "sex": "女"
}]

App.js

// 定义url 为接口值
let url = 'https://5b5e71c98e9f160014b88cc9.mockapi.io/api/v1/lists';
// 使用get的方法请求接口
axios.get(url)  
// 回调函数 .then 为如果请求成功了将返回res
  .then((res) => {
      let data = res.data;
      // 更新状态,将接口中的数据赋值给gisUrl
      this.setState({
        gisUrl : data[0].name
      })
    }
  )  
// 回调函数 .catch 捕获错误信息并将错误信息打印出来  
  .catch((error) => {
    console.log(error);
  })

fetch数据请求

fetch数据请求不需要安装依赖包。

本地数据请求

首先我们访问的本地 json 文件放在 public 文件夹下。(记住:一定要放在 public 文件夹下面,不能放在 src 下面,放在 src 下面是找不到的)
创建一个 data.json 的文件
data.json

[{
"name":"陈威",
"password":"123456"},
 {"name":"超帆",
"password":"123456"
}]

请求核心代码

// 定义url
let url = "./data.json";
fetch(url,{
  // 定义是GET请求还是POST请求
  method:"GET",
  // 允许跨域请求
   mode:'cors',
  // 设置请求头(下面的意思是只能请求json格式的数据)
  headers: {
    "Content-Type": "application/json"
  }
})
  // 请求成功返回数据
.then(function(response) {
  // 将请求来的数据进行json解析
  return response.json();
})
.then(function(data){
  console.log(data);
})
  // 请求失败返回错误信息
.catch(function(e){
  console.log("Oops, error",e);
});

服务端数据请求

在开发中,我们会访问服务端的数据,和本地数据请求类似。

const url = "";
const canshu1 = "";
const canshu2 = ""; 
fetch(url, {
    // POST请求
    method: 'POST',
    // 允许cors跨域请求
    mode: 'cors',
    // fetch事实标准中可以通过Header相关api进行设置
    headers: {
      // 
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    // 添加到url里的参数
    body: "canshu1="+canshu1+"&&canshu2="+canshu2
  })
  // 如果成功了进行json解析
  .then(response => response.json())
  // 我们实际上获取的其实的data里的数据
  .then(function(data){
    return data;
  })
  // 如果失败了就返回错误信息
  .catch((ex) => console.log('parsing failed', ex))  

fetchJsonp

安装依赖 npm install fetch-jsonp ;
引用依赖 import fetchJsonp from 'fetch-jsonp';
首先安装项目依赖
此方法只支持GET方法,而且方法基于ES6的Promise实现:

fetchJsonp('/访问的地址.jsonp')
.then(function(response) {
 return response.json()})
.then(function(json) {
 console.log('parsed json', json); })
.catch(function(ex) {
 console.log('parsing failed', ex) })

这样就可以实现跨域请求,还支持then方法异步处理,是不是特别简单。

Last modification:October 19th, 2019 at 04:41 pm
如果觉得我的文章对你有用,请随意赞赏