使用reqwest进行异步请求数据

是的没错,就是reqwest而不是request。下面我们来看一下reqwest的使用方法
npm安装相关依赖包

npm i --save reqwest

 普通的reqwest和axios差不多:废话不多说直接上代码

import React, { Component } from 'react'

import reqwest from 'reqwest';
const fakeDataUrl = '/api/noreturn.json';
export default class index extends Component {
    componentDidMount() {
        // 用于更新fetchData传来的数据,此步骤在生命周期函数中进行
        this.fetchData(res => {
            this.setState({
              data: res.results,
            });
        });
    }
    // 封装用于reqwest请求数据函数
    fetchbooks = (callback) => {
        reqwest({
            // 请求地址
            url: fakeDataUrl,
            // 请求的数据类型
            type: 'json',
            // 请求方式
            method: 'post',
            // 内容类型
            contentType: 'application/x-www-form-urlencoded',
            // 允许跨域请求
            crossOrigin: true,  
            success: res => {
                callback(res)
            },
            error: res => {
                callback(res);
            },
        });
    }
    render() {
        return (
            <div>
                
            </div>
        )
    }
}

另外扩展 reqwest 的jsonp请求

reqwest({
  url: 'path/to/json', 
  type: 'jsonp',
  method: 'get', // jsonp请求,method可不写,写成post,依然会被浏览器默认为get
  error: function (err) { }
  success: function (resp) { }
})
Last modification:June 28th, 2019 at 01:23 pm
如果觉得我的文章对你有用,请随意赞赏