umi + axios 请求数据(一)

2020-04-24  本文已影响0人  搬砖笔记

本文档主要是讲解一些axios的基础配置,实际umi项目中一般会采用dva/fetch去请求数据。如果是想建立简单的数据请求可以采用这篇文档去配置;实际的项目中如果,如果项目的业务较复杂,想在umi项目中引入axios发起数据请求。可以参考后续文档(二)持续更新中......

引入 安装 axios
  yarn add axios  
编写axios文件

在项目src文件下,新建文件夹apiConfig,新增文件request.js, 编写axios请求数据时,需要对URL、及返回结果的处理:

import axios from 'axios'

// 基本配置
axios.defaults.baseURL = "http://localhost:8001/ucc/"   //api前缀
 
const axios= axios.create({
    xsrfCookieName: 'xsrf-token' ,  // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
    timeout: 1000,    // 如果请求话费了超过 `timeout` 的时间,请求将被中断
    proxy: {    // 'proxy' 定义代理服务器的主机名称和端口
    host: '10.10.10.198',
    port: 9000,
  },
});
 
instance.interceptors.request.use(function (config) {
  return config;
}, function (error) {
  return Promise.reject(error);
});
 
instance.interceptors.response.use(function (response) {
  return response     // 下节详述
}, function (error) {
  return Promise.reject(error);
});
export default axios;

相应结构

某个请求的响应包含以下信息:

{
  // `data` 由服务器提供的响应
  data: {},

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',

  // `headers` 服务器响应的头
  headers: {},

   // `config` 是为请求提供的配置信息
  config: {},
 // 'request'
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

在项目中使用 index.js

import  axiosfrom '@/utils/request';
import { stringify } from 'qs';     // 一个查询字符串解析和字符串化库,增加了一些安全性。


  componentDidMount() {
    let params={
      pageSize:10,
      pageIndex:1,
    }
// 执行get请求:
    axios.get(`ucc/modules/basic/part_info/partInfoList?${stringify(params)}`)
       .then((res) => {
        console.log('res', res)
    });
// 执行post请求:
    axios.get(`ucc/modules/basic/part_info/partInfoList`, {
        pageSize:10,
        pageIndex:1,
     })
       .then((res) => {
        console.log('res', res)
    })
  }
上一篇 下一篇

猜你喜欢

热点阅读