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 });
            }
        });
    };