axios全局使用 react

2019-03-12 21:30:15 fenglangwangyi 阅读数 378

最新几天学了一下react,发现了几个问题,估计新入坑的同学们也会遇到,下面我先列出来几点

1、请求跨域问题

2、如何发起请求

3、axios的简单封装

全局安装create-react-app脚手架,帮助我们新建react项目

 

npm install -g create-react-app

然后创建react项目

create-react-app xxx项目名

然后安装依赖,并且运行react项目

安装 npm install

运行 npm start

首先我们解决跨域的问题

打开项目生成的package.json文件,修改文件内容如下

如果你赖一点可以这样写

完整写法

这样就可以解决跨域问题。

接下来开始讲一下如果在react中使用axios

首先安装axios

npm install axios --save-dev

方法一:

然后在我们的src目录下新建一个server.js的文件写下如下代码

然后我们就可以在react组件上使用我们的axios

随便写一个react组件,然后引进我们的刚刚封装的server.js,先写一个登录的函数,然后在组件渲染完之后执行该函数

打开浏览器查看返回结果

方法二:

我们可以先把所有的api都列出来,然后在用export导出去,如下

组件中使用

浏览器结果

看到上面的结果,说明我们已经成功决解跨域问题并且拿到了后台返回的数据。是不是很简单,赶紧自己动手试一试吧。

2019-06-19 23:00:52 qq_41287423 阅读数 4882

React通过axios请求数据

一、全局安装axios:
npm install axios
二、创建axios.js文件(配置了过滤器,请求响应)

import Axios from 'axios'
import {Component} from 'react'
Component.prototype.$axios=Axios //将axios挂载到Component上,以供全局使用

//配置过滤器请求响应(通过查npm官网,axios文档)
Axios.interceptors.response.use(function (response) {
    return response.data;//只获取data数据
  }, function (error) {
    return Promise.reject(error);
  });

并在index.js中引入,import ‘相对路径/axios’

三、若出现跨域:
①最简单直接的方法:
在package.json中,直接配置:“proxy”:“http://47.95.207.1:8080”,
缺点:只能设置一个跨域,多个跨域不可取
②在config —> webpackDevServer.config.js中,找到proxy进行配置:

//设置跨域小暗号:/hehe
 proxy:{
      '/hehe':{
        target:'http://47.95.207.1:8080',
        changeOrigin:true,
        pathRewrite:{'^/hehe':''}
      }
    },

四、在组件中请求数据:

 componentDidMount(){
        //请求api:  http://47.95.207.1:8080/api/getHome  跨域小暗号:/hehe
        this.$axios.get('/hehe/api/getHome')
        .then((res)=>{
            console.log(res)
        })
        .catch((err)=>{
            console.log(err)
        })
    }
2019-05-10 13:53:13 zhuming3834 阅读数 1127

之前在vue中使用axios《vue 开发axios的封装async/await》。这里其实就是把之前vue中封装的axios 移植过来的。基本没变。这里不再多说了。

封装

// 网络请求 可以使用 async/await

// 引入 axios
import axios from 'axios'

// 测试地址
// axios.defaults.baseURL = '';    
// 线上地址
// axios.defaults.baseURL = '';  
// demo地址
// axios.defaults.baseURL = '';  
axios.defaults.timeout = 10000;  // 超时时间  10s

var http = {

  /** get 请求
   * @param  {接口地址} url
   * @param  {请求参数} params
   */
  get: function(url,params){
    params = params || {}
    return new Promise((resolve,reject) => {
      axios.get(url,{
        params:params
      })
      .then((res) => {
        resolve( res.data);
      })
      .catch((error) => {
        reject( error );
      });
    })
  },
  /** post 请求
   * @param  {接口地址} url
   * @param  {请求参数} params
   */
  post: function(url,params){
    params = params || {};
    return new Promise((resolve,reject) => {
      axios.post(url,params)
      .then((res) => {
        resolve( res.data );
      })
      .catch((error) => {
        reject( error );
      });
    })
  }
}

export default http


使用

import React from 'react';
import { Link } from 'react-router-dom';
import http from '../assets/js/http'

class Home extends React.Component {

    // 获取IP
    async getMyIP(){
        let baseUrl = "https://api.apiopen.top/EmailSearch";
        let params = {
            number: '1012002'
        }
        var data = await http.get(baseUrl,params);
    }
    render() {
        return (
            <div className='home'>
                <Link to="/detail">Home</Link>
                我是首页
            </div>
        );
    }
    componentDidMount() {
        this.getMyIP();
    }
}

export default Home;
2019-08-03 18:15:33 liuyuhua666 阅读数 688

在使用 axios 发送请求的时候,接口地址每次都要写 http://localhost:8080这样类似的url ,太繁琐。那么我们要如何解决呢?
通过 axios 配置,统一处理 baseURL,baseURL: ‘http://localhost:8080/

import axios from 'axios'
const request= axios.create({
  baseURL: 'http://localhost:8080'
})

// 添加请求拦截器
request.interceptors.request.use(config => {
 // 写你想要处理的代码,注意:config一定要返回,否则会报错
 // ...
  return config
})
// 添加响应拦截器
request.interceptors.response.use(res => {
  // 处理响应的代码写在这里,注意:res一定要返回,否则会报错
  return res
})
export { request}

这样在别的地方就能引入这个文件调用request了
本来是这样:

axios.get('http://localhost:8080/aa/bb')

然后就能写成这样:

axios.get('/aa/bb')

看起来是少写了一些代码是不是?,但是项目是分开发版本和生产版本的,现在baseURL写死成了开发版本的,那生产版本的怎么办呢,难道到时候再改过来吗?,显然不合适,所有在项目一开始就要配置好环境变量,让它能够同时适应各个版本

环境变量的配置:https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

首先在根目录也就是与package.json文件同级的目录创建两个以 .env开头的文件,因为以点符号开头,我用的是vscode,所以需要安装一个插件叫 DotENV
在这里插入图片描述
两个文件的名字分别是用于开发版本的 .env.development 和用户生产版本的 .env.production:
在这里插入图片描述
在这里插入图片描述

然后在两个文件中定义以 REACT_APP_ 开头的变量,注意,一定要以 REACT_APP_ 开头,否则环境读取不到:
在这里插入图片描述
创建REACT_APP_URL变量,在两个文件中分别设置它们的url,
在.env.development文件中设置开发时的url,比如:

REACT_APP_URL=http://localhost:8080

在.env.production文件中设置生产时的url,比如:

REACT_APP_URL=http://api.xxx.com

然后在src中创建utils文件夹,在utils中创建url.js文件专门用于导出BASE_URL,
在这里插入图片描述
在url.js中将 BASE_URL 导出:
在这里插入图片描述
注意:配置的变量对应的值需要通过 process.env 才可以拿得到
在这里插入图片描述
现在,不管是生产环境还是开发环境都可以通过 BASE_URL 拿到对应的url,然后将它与axios结合起来:
在url.js的同级目录创建api.js文件
在这里插入图片描述
自此,不管开发还是 生产环境都可以导入api.js文件拿到已经设置了 baseURL 的axios进行ajax请求发送了

2020-03-04 13:49:55 yitian_z 阅读数 339

React中安装并引入axios依赖

在React项目中使用axios请求,首先需要安装axios:

npm install axios --save

然后在react文件中使用typescript方式导入axios依赖:

import axios from 'axios';

使用axios进行GET请求

axios中使用GET请求时有两中方式:

  • 一种是使用axios.get的方式进行
  • 一种是使用axios(config { ... })的方式进行

使用axios.get方式

使用封装的axios.get进行请求的常用格式如下:

// Make a request for a user with a given ID
axios.get('/getUser?id=12345')
  .then(function (response) {
    // handle success
    console.log(response);

    // update state or do something
    this.setState({
      // ...
    })
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/getUser', {
    params: { // 这里的参数设置为URL参数(根据URL携带参数)
      id: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/getUser?id=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

使用axios(config {...})

使用axios(config {...}) 的方式发送GET请求格式如下:

axios({
  method: 'get',
  url: '/getUser',
  params: {
    id: 12345,
  }
})
  .then(function (response) {
    console.log(response);
  });

以上的get请求发送的URL均为如下:

http:HOST_IP:XXXX/getUser?id=12345

使用axios进行POST请求

同GET请求一样,使用POST也有两种请求方式。

使用axios.post

axios.post('/createUser', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

使用axios(config {...})

    // Send a POST request
    axios({
      method: 'post',
      url: '/createUser',
      data: { // 这里data中的参数为requestBody参数,服务端需要使用@RequestBody注解进行获取
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    }).then(function (response) {
      console.log(response);
    }).catch(function (error) {
      console.log(error);
    });

需要注意的是,在使用axios(config {})方式进行GET或POST请求发送时,GET请求中params为URL参数,POST请求中data为RequestBody参数,在服务端需要使用@RequestBody注解接收,Spring Boot能够自动解析为Java相应的对象。

同时发送多个请求

使用axios也可以一次发送多个请求:

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

详细config对象配置项

在axios的readme文档中,有对config对象的具体配置说明,如下:

{
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `baseURL` will be prepended to `url` unless `url` is absolute.
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` are the URL parameters to be sent with the request
  // Must be a plain object or a URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function in charge of serializing `params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
  
  // syntax alternative to send data into the body
  // method post
  // only the value is sent, not the key
  data: 'Country=Brasil&City=Belo Horizonte',

  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000, // default is `0` (no timeout)

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  // Please note that only HTTP Basic auth is configurable through this parameter.
  // For Bearer tokens and such, use `Authorization` custom headers instead.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` indicates the type of data that the server will respond with
  // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  //   browser only: 'blob'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` allows handling of progress events for uploads
  // browser only
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  // browser only
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength` defines the max size of the http response content in bytes allowed
  maxContentLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // `proxy` defines the hostname and port of the proxy server.
  // You can also define your proxy using the conventional `http_proxy` and
  // `https_proxy` environment variables. If you are using environment variables
  // for your proxy configuration, you can also define a `no_proxy` environment
  // variable as a comma-separated list of domains that should not be proxied.
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
}

axios的返回值对象response

axios在进行请求后得到的response对象格式如下:

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the HTTP headers that the server responded with
  // All header names are lower cased and can be accessed using the bracket notation.
  // Example: `response.headers['content-type']`
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

当在请求后使用then方法时,可以获取response对象的各个属性值,其中data即为服务端返回的相应对象:

axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

axios的全局配置

在使用axios时,可以对axios对象进行全局的设置,该设置会应用于axios所在当前javascript类中的所有axios请求中,例如如下的设置:

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

 axios的单一实例化配置

如果不需对axios进行全局设置,则可以在使用某个axios对象时,进行单一对象的设置,例如如下:

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

axios拦截器的使用

可以使用axios拦截器来在发送请求之前或在响应response之前(then方法)来拦截请求并进行自定义的设置,定义request和response拦截器示例如下:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

当需要删除拦截器时,进行如下操作:

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

也可以将定义的拦截器添加到自定义的axios实例中: 

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

以上部分资料参考自axios文档,具体参见:https://github.com/axios/axios