How to use axios - 10 common examples

To help you get started, we’ve selected a few axios examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github matestack / matestack-ui-core / lib / matestack / ui / vue_js / components / action.js View on Github external
sendRequest: function(){
      const self = this
      axios({
          method: self.componentConfig["method"],
          url: self.componentConfig["action_path"],
          data: self.componentConfig["data"],
          headers: {
            'X-CSRF-Token': document.getElementsByName("csrf-token")[0].getAttribute('content')
          }
        }
      )
      .then(function(response){
        if (self.componentConfig["success"] != undefined && self.componentConfig["success"]["emit"] != undefined) {
          matestackEventHub.$emit(self.componentConfig["success"]["emit"], response.data);
        }

        // transition handling
        if (self.componentConfig["success"] != undefined
          && self.componentConfig["success"]["transition"] != undefined
github flow-typed / flow-typed / definitions / npm / axios_v0.16.x / test_axios-v0.16.js View on Github external
firstName: 'Fred',
    lastName: 'Flintstone'
  }
}).then(r => {
  // $ExpectError
  (r.status: string);
});

class AxiosExtended extends axios.Axios {
  specialPut(...args) {
    return super.put(...args);
  }
}

const extended = new AxiosExtended();
axios.all([
  extended.specialPut('foo')
    .then((r) => {
        // $ExpectError
        (r.statusText: number)
    }),
    Promise.reject(12)
]).then(([a, b]) => {
    // $ExpectError
    (a: string);
})
github oracle-quickstart / oci-cloudnative / src / api / api / user / index.js View on Github external
app.post("/login", async (req, res, next) => {
        try {
            // client uses basic-auth
            const auth = req.get('authorization');
            const [username, password] = Buffer.from(auth.replace(/^\w+\s/, ''), 'base64').toString('utf8').split(':');
            const { data: user } = await axios.post(endpoints.loginUrl, {
                username,
                password,
            });
            helpers.setAuthenticated(req, res, user.id)
                .status(200)
                .send('OK');
        } catch (e) {
            res.status(401).end();
        }
    });
github 60late / vue-nodejs-blog / src / fetch / api.js View on Github external
import axios from 'axios'
import qs from 'qs';
import store from '../store/'
import router from '../router/'
// axios 配置
axios.defaults.timeout = 10000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8;multipart/form-data;boundary=----WebKitFormBoundaryeOOd9EoQVo6B4Tgb';
//    /api这个位置在config/index.js里面设置了代理,指向 localhost:8081/api这个后台地址
axios.defaults.baseURL = 'http://localhost:8081/api';

// http request 拦截器
axios.interceptors.request.use(
    config => {
		if (store.state.token) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
			config.headers.Authorization = `Bearer ${store.state.token}`;
		}
		console.log(config);
        return config;
    },
    err => {
        return Promise.reject(err);
    });
github tuwq / blog / blog_back / src / router / carry.js View on Github external
import { _set,_get,_remove } from 'base/js/cookie'
// 每次请求携带LOGIN_TOKEN
axios.interceptors.request.use(
    config => {
        if (_get('_TOKEN_')) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
            config.headers._TOKEN_  = _get('_TOKEN_');
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// 每次检查TOKEN过期
axios.interceptors.response.use(
    response => {
    	if ( response.data.code == CONSTANT_CODE.TOKEN_MATURITY_LOGIN || response.data.code == CONSTANT_CODE.TOKEN_NOTUSER ) {
    		_remove('_TOKEN_')
            store.commit(types.SET_NOW_USER_INFO,undefined)
            router.replace({
              path: '/login',
              query: {redirect: router.currentRoute.fullPath}
            })
    	} else if (response.data.code == CONSTANT_CODE.TOKEN_MATURITY) {
            _remove('_TOKEN_')
            store.commit(types.SET_NOW_USER_INFO,undefined)
        }
        return response;
    },
    err => {
    	return Promise.reject(err);
github Zkliang1991 / Zkliang1991.github.io / 1901 / vue / hechenxi / src / utils / ajax.js View on Github external
//         text: '加载中...',
    //         spinnerType: 'triple-bounce'
    //     });
    return config;
}, function (error) {
    // Do something with request error
    Toast({
        message: "未知错误",
        duration: 500
    })
    return Promise.reject(error);
});


// // 响应拦截器 response 
axios.interceptors.response.use(function (response) {
    console.log(response)
    // Indicator.close();
    Toast({
        message: response.data.msg,
        duration: 500
    });
    if (response.data.code == '401') {
        router.push({
            name: 'login'
        })
    }
    return response;
}, function (error) {
    Toast({
        message: "未知错误",
        duration: 500
github LinWeb / blog / app / src / axios / index.js View on Github external
//     if (!checkLogin()) {
    //         window.location = '#login'
    //         return new Error('no login')
    //     }
    // }
    // config.withCredentials = true  // 设置浏览器自动存储服务器cookie
    let token = localStorage.getItem('token')
    if (token) {
        config.headers.Authorization = 'Bearer ' + token
    }
    return config
}, (error) => {
    return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    if (response.data.status !== 1) {
        message.error(response.data.message);
    }
    return response.data
}, function (error) {
    console.log(error)
    // Toast.fail(error.message, 1);
    return Promise.reject(error);
});


export default axios
github aitexiaoy / Strawberry-Wallpaper / src / get-image / pola.js View on Github external
return new Promise((resolve) => {
        axios.request({
            url,

            // `method` 是创建请求时使用的方法
            method: 'get', // 默认是 get
            // `onDownloadProgress` 允许为下载处理进度事件
            onDownloadProgress(progressEvent) {
                // 对原生进度事件的处理
                console.log('--------------------下载图片进度:')
                // console.log(progressEvent)
            },
        }).then(async (result) => {
            if (result.status === 200) {
                // eslint-disable-next-line no-param-reassign
                result = result.data.data
            } else {
                return
github netlify / www-post-scheduler / lib / github / updateGithubComment.js View on Github external
module.exports = function updateGithubComment(commentID, message) {
  /* /repos/:owner/:repo/issues/comments/:id */
  const commentAPI = `https://api.github.com/repos/${GITHUB_REPO}/issues/comments/${commentID}`
  return axios.patch(commentAPI, {
    "body": message,
  }, config).then(function(response) {
    console.log('patch response', response)
    return response
  });
}
github EventKit / eventkit-cloud / eventkit_cloud / ui / static / ui / app / actions / userGroupsActions.fake.js View on Github external
}).catch((error) => {
            if (axios.isCancel(error)) {
                console.log(error.message);
            } else {
                mock.restore(); //// JUST FOR MOCKING
                dispatch({ type: types.FETCH_GROUPS_ERROR, error: error.response.data });
            }
        });
    };