GET 请求

  1. // Make a request for a user with a given ID
  2. axios.get('/user?ID=12345')
  3. .then(function (response) {
  4. console.log(response);
  5. })
  6. .catch(function (error) {
  7. console.log(error);
  8. });
  9. // Optionally the request above could also be done as
  10. axios.get('/user', {
  11. params: {
  12. ID: 12345
  13. }
  14. })
  15. .then(function (response) {
  16. console.log(response);
  17. })
  18. .catch(function (error) {
  19. console.log(error);
  20. });
  21. axios({
  22. method: 'get',
  23. url: 'http://bit.ly/2mTM3nY',
  24. responseType: 'stream'
  25. })
  26. .then(function(response) {
  27. response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  28. });

POST 请求

  1. axios.post('/user', {
  2. firstName: 'Fred',
  3. lastName: 'Flintstone'
  4. })
  5. .then(function (response) {
  6. console.log(response);
  7. })
  8. .catch(function (error) {
  9. console.log(error);
  10. });
  11. // Send a POST request
  12. axios({
  13. method: 'post',
  14. url: '/user/12345',
  15. data: {
  16. firstName: 'Fred',
  17. lastName: 'Flintstone'
  18. }
  19. });

并行请求

  1. function getUserAccount() {
  2. return axios.get('/user/12345');
  3. }
  4. function getUserPermissions() {
  5. return axios.get('/user/12345/permissions');
  6. }
  7. axios.all([getUserAccount(), getUserPermissions()])
  8. .then(axios.spread(function (acct, perms) {
  9. // Both requests are now complete
  10. }));

创建实例

  1. var instance = axios.create({
  2. baseURL: 'https://some-domain.com/api/',
  3. timeout: 1000,
  4. headers: {'X-Custom-Header': 'foobar'}
  5. });

Response

  1. axios.get('/user/12345')
  2. .then(function(response) {
  3. console.log(response.data);
  4. console.log(response.status);
  5. console.log(response.statusText);
  6. console.log(response.headers);
  7. console.log(response.config);
  8. });

Config

  1. // Global axios defaults
  2. axios.defaults.baseURL = 'https://api.example.com';
  3. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  4. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  5. // Custom instance defaults
  6. // Set config defaults when creating the instance
  7. var instance = axios.create({
  8. baseURL: 'https://api.example.com'
  9. });
  10. // Alter defaults after instance has been created
  11. instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  12. // Config order of precedence
  13. // Create an instance using the config defaults provided by the library
  14. // At this point the timeout config value is `0` as is the default for the library
  15. var instance = axios.create();
  16. // Override timeout default for the library
  17. // Now all requests will wait 2.5 seconds before timing out
  18. instance.defaults.timeout = 2500;
  19. // Override timeout for this request as it's known to take a long time
  20. instance.get('/longRequest', {
  21. timeout: 5000
  22. });

拦截器

  1. // Intercept request/responses
  2. // Add a request interceptor
  3. axios.interceptors.request.use(function (config) {
  4. // Do something before request is sent
  5. return config;
  6. }, function (error) {
  7. // Do something with request error
  8. return Promise.reject(error);
  9. });
  10. // Add a response interceptor
  11. axios.interceptors.response.use(function (response) {
  12. // Do something with response data
  13. return response;
  14. }, function (error) {
  15. // Do something with response error
  16. return Promise.reject(error);
  17. });
  18. // Remove interceptor
  19. var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
  20. axios.interceptors.request.eject(myInterceptor);
  21. // Custom instance interceptors
  22. var instance = axios.create();
  23. instance.interceptors.request.use(function () {/*...*/});

错误处理

  1. // Catch error
  2. axios.get('/user/12345')
  3. .catch(function (error) {
  4. if (error.response) {
  5. // The request was made and the server responded with a status code
  6. // that falls out of the range of 2xx
  7. console.log(error.response.data);
  8. console.log(error.response.status);
  9. console.log(error.response.headers);
  10. } else if (error.request) {
  11. // The request was made but no response was received
  12. // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
  13. // http.ClientRequest in node.js
  14. console.log(error.request);
  15. } else {
  16. // Something happened in setting up the request that triggered an Error
  17. console.log('Error', error.message);
  18. }
  19. console.log(error.config);
  20. });
  21. // Custom HTTP status code error
  22. axios.get('/user/12345', {
  23. validateStatus: function (status) {
  24. return status < 500; // Reject only if the status code is greater than or equal to 500
  25. }
  26. })

取消请求

  1. // Cancel request with cancel token
  2. var CancelToken = axios.CancelToken;
  3. var source = CancelToken.source();
  4. axios.get('/user/12345', {
  5. cancelToken: source.token
  6. }).catch(function(thrown) {
  7. if (axios.isCancel(thrown)) {
  8. console.log('Request canceled', thrown.message);
  9. } else {
  10. // handle error
  11. }
  12. });
  13. axios.post('/user/12345', {
  14. name: 'new name'
  15. }, {
  16. cancelToken: source.token
  17. })
  18. // cancel the request (the message parameter is optional)
  19. source.cancel('Operation canceled by the user.');
  20. // Create cancel token
  21. var CancelToken = axios.CancelToken;
  22. var cancel;
  23. axios.get('/user/12345', {
  24. cancelToken: new CancelToken(function executor(c) {
  25. // An executor function receives a cancel function as a parameter
  26. cancel = c;
  27. })
  28. });
  29. // cancel the request
  30. cancel();