using node axios

https://www.npmjs.com/package/axios

Simple example

The return is a promise, if it is asynchronous, you need to use await

structure of the response

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

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

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

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

  // `config` 是为请求提供的配置信息
  config: {}
}
let axios = require('axios')
axios.defaults.baseURL = 'http://www.ahaoboy.cn'

let res = axios.get('/get_hot').then(
    (res) => {
        console.log('success', res.data)
    },
    (err) => {
        console.log('err', err)
    }
)

console.log(res)

 

Common APIs

https://www.kancloud.cn/yunye/axios/234845

execute  GET request

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

execute  POST request

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

Execute multiple concurrent requests

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) {
    // 两个请求现在都执行完成
  }));

 

let axios = require('axios')
axios.defaults.baseURL = 'http://www.ahaoboy.cn'

let movie1 = () => {
    return axios.get('/get_movie', {
        params: {
            movie_id: 1408312
        }
    })
}
let movie2 = () => {
    return axios.get('/get_movie', {
        params: {
            movie_id: 26140405
        }
    })
}
let movie3 = () => {
    return axios.get('/get_movie', {
        params: {
            movie_id: 10355329
        }
    })
}


axios.all([movie1(), movie2(), movie3()])
    .then(axios.spread(function (req1, req2, req3) {
        // 两个请求现在都执行完成
        console.log(req1.data);
        console.log(req2.data);
        console.log(req3.data);
    }));

axios API

Requests can be created by  axios passing the relevant configuration to

axios(config)

// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

axios(url[, config])

// 发送 GET 请求(默认的方法)
axios('/user/12345');

request method alias

For convenience, aliases are provided for all supported request methods

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

NOTE

When using the alias method  url, none methodof data these properties have to be specified in the configuration.

Concurrency

Helper functions for handling concurrent requests

axios.all(iterable)

axios.spread(callback)

 

Configured defaults/defaults

You can specify configuration defaults that will be used on individual requests

Global axios defaults

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';

Custom instance defaults

// 创建实例时设置配置的默认值
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 在实例已创建后修改默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Configuration priority

Configurations are merged in a priority order. The order is:  lib/defaults.js defaults in the library found, then the properties of the instance  , and finally the  parameters defaults of the request  . configThe latter will take precedence over the former. Here is an example:

// 使用由库提供的配置的默认值来创建实例
// 此时超时配置的默认值是 `0`
var instance = axios.create();

// 覆写库的超时默认值
// 现在,在超时前,所有请求都会等待 2.5 秒
instance.defaults.timeout = 2500;

// 为已知需要花费很长时间的请求覆写超时设置
instance.get('/longRequest', {
  timeout: 5000
});

interceptor

 Intercept requests or responses  then before  they are processed.catch

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

If you want to remove the interceptor later, you can do this:

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

You can add interceptors for custom axios instances

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

error handling

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 请求已发出,但服务器响应的状态码不在 2xx 范围内
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

validateStatus A custom HTTP status code error range can be defined using  configuration options.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // 状态码在大于或等于500时才会 reject
  }
})

Cancel

 Cancel request with  cancel token

Axios' cancel token API is based on the cancelable promises proposal , which is still in its first phase.

A cancel token can be created using a  CancelToken.source factory method like this:

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // 处理错误
  }
});

// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');

A cancel token can also be created by passing an executor function to  CancelToken the constructor:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c;
  })
});

// 取消请求
cancel();

Note : Multiple requests can be cancelled with the same cancel token

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324993078&siteId=291194637