EzDev.org

axios

axios - Promise based HTTP client for the browser and node.js


Switching from vue-resource to axios

With vue-resource, we could set the root url in main.js like so:

Vue.http.options.root = 'http://localhost:3000/api'

I tried replacing that with:

axios.defaults.baseURL = 'http://localhost:3000/api';
Vue.prototype.$http = axios

However, now my post calls don't work as expected, and Vue.http.post throws an error.

How is this achieved?


Source: (StackOverflow)

Handling api calls in Redux with Axios

Good evening everybody!

I'm a total beginner in React and Redux so please bear with me if this sounds totally stupid. I'm trying to learn how I can perform some API calls in Redux and it's not going all to well. When I console log the request from the action creator the promise value is always "undefined" so I'm not sure if I'm doing this correctly.

My goal is to grab the information from the data inside the payload object and display them inside the component. I've been trying to get this to work for the past days and I'm totally lost.

I'm using Axios for and redux-promise to handle the call.

Any help will be greatly appreciated.

Here's the output from the console.

enter image description here

enter image description here

Action Creator

import axios from 'axios';
export const FETCH_FLIGHT = 'FETCH_FLIGHT';

export function getAllFlights() {

const request = axios.get('http://localhost:3000/flug');
console.log(request);
  return {
    type: FETCH_FLIGHT,
    payload: request
    };
}

Reducer

import { FETCH_FLIGHT } from '../actions/index';

export default function(state = [], action) {
  switch (action.type) {
    case FETCH_FLIGHT:
    console.log(action)
      return [ action.payload.data, ...state ]
    }
   return state;
  }

Component

import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getAllFlights } from '../actions/index';
import Destinations from './Destinations';

class App extends Component {

componentWillMount(){
  this.props.selectFlight();
}

constructor(props) {
 super(props);
  this.state = {
 };
}

render() {
  return (
    <div>
    </div>
    );
 }

function mapStateToProps(state) {
 return {
   dest: state.icelandair
  };
}

function mapDispatchToProps(dispatch) {
 return bindActionCreators({ selectFlight: getAllFlights }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);

Source: (StackOverflow)

Return Promise from Axios?

I am wondering how do I return a promise form Axios? I am not sure if I need to use an Interceptors?

I have this code right now

export function fetchStorage() {
    return function (dispatch) {
      return new Promise(function(resolve, reject) {
        if (1 === 1) {
          resolve('it works!');
        } else {
          reject(':(');
        }
      });
    };
}

and

this.props.fetchStorage().then(function() {
           console.log('then');
        });

Now say I want to change the fetchStorage to do something via ajax and I would have it like

 var instance = axios.create({
            baseURL: 'http://localhost:54690/api',
            timeout: 2000,

        });

        instance.get('/Storage/Get')
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });

how do I return the promise instead of doing it here?

Edit

Just for clarification why I am doing this I have something like this

  componentWillMount() {
        this.props.setPreLoader(true);
        this.props.fetchStorage().then(function() {
           this.props.setPreLoader(false);
        });
    }

export function fetchStorage() {
    return function (dispatch) {
        return new Promise(function (resolve, reject) {
            axiosInstant.get('/Storage/Get')
                .then(function (response) {
                    let payload = response.data;
                    console.log(payload);
                    dispatch({ type: actions.FETCH_STORAGE, payload: { storages: payload } });
                })
                .catch(function (error) {
                    console.log(error);
                });
        });
    };
}

Source: (StackOverflow)

How to log all axios calls from one place in code

I am using axios for a react application and I would like to log all axios calls that I'm making anywhere in the app. I'm already using a single global instance of axios via the create function and I am able to log a generic console.log. However I would like more info like function being called, parameters, etc.


Source: (StackOverflow)

Ajax post a file from a form with Axios

Using raw .html when I post a file to a flask server using the following I can access files from the flask request global:

<form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data>
    <input type="file" id="file" name="file">
    <input type=submit value=Upload>
</form>

In flask:

def post(self):
    if 'file' in request.files:
        ....

When I try to do the same with Axios the flask request global is empty:

<form id="uploadForm" enctype="multipart/form-data" v-on:change="uploadFile">
<input type="file" id="file" name="file">
</form>

uploadFile: function (event) {
    const file = event.target.files[0]
    axios.post('upload_file', file, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
    })
}

If I use the same uploadFile function above but remove the headers json from the axios.post method I get in the form key of my flask request object a csv list of string values (file is a .csv). How can I get a file object sent via axios?


Source: (StackOverflow)

Returning an Axios Promise from function

Can someone please explain why returning an Axios promise allows for further chaining, but returning after applying a then()/catch() method does not?

Example:

const url = 'https://58f58f38c9deb71200ceece2.mockapi.io/Mapss'
    
function createRequest1() {
  const request = axios.get(url)

  request
  .then(result => console.log('(1) Inside result:', result))
  .catch(error => console.error('(1) Inside error:', error))

  return request
}

function createRequest2() {
  const request = axios.get(url)

  return request
  .then(result => console.log('(2) Inside result:', result))
  .catch(error => console.error('(2) Inside error:', error))
}

createRequest1()
.then(result => console.log('(1) Outside result:', result))
.catch(error => console.error('(1) Outside error:', error))

createRequest2()
.then(result => console.log('(2) Outside result:', result))
.catch(error => console.error('(2) Outside error:', error))
<script src="https://unpkg.com/axios@0.16.1/dist/axios.min.js"></script>

https://jsfiddle.net/nandastone/81zdvodv/1/

I understand that Promise methods should return a value to be chained, but why is there a difference between these two return methods?


Source: (StackOverflow)

What are the differences between Redux-Thunk and Redux-Promise when used with Axios apis?

I have been using React , Redux since few months now. One of the most confusing part of the ecosystem is the async data flow. There are many great solutions available and choosing the right solution for your problem is the tough part.

In my application, the action creators mostly have async axios [ajax] calls to my back-end apis. Injecting Redux-Promise as a middleware resolves the issue of async data flow.

Considering the scalable app, I might need to chain multiple axios calls in my action creator. I think I can still use Redux-Promise as a middleware and this would take care of async data flow in my app.

In general the team is more inclined towards using Redux-Thunk, which I feel more complicated syntax for this problem. I need suggestions in evaluating these 2 frameworks considering most of my action creators are making axios calls(promises) only. I have seen a great deal of discussion on Redux-thunk here. I understood how thunk can be useful. . But I need more clarification evaluating Redux-Promise and Redux-Thunk together when used for Promises only. Which middleware is better in such situation and why? What advantages do I get using Redux-Thunk over Redux-Promise ? Or there is none?


Source: (StackOverflow)

Axios get in url works but with second parameter as object it doesn't

I'm trying to send GET request as second parameter but it doesn't work while it does as url.

This works, $_GET['naam'] returns test:

export function saveScore(naam, score) {
  return function (dispatch) { 
    axios.get('http://****.nl/****/gebruikerOpslaan.php?naam=test')
      .then((response) => {
        dispatch({type: "SAVE_SCORE_SUCCESS", payload: response.data})
      })
      .catch((err) => {
        dispatch({type: "SAVE_SCORE_FAILURE", payload: err})
      })
  }
};

But when I try this, there is nothing in $_GET at all:

export function saveScore(naam, score) {
  return function (dispatch) { 
    axios.get('http://****.nl/****/gebruikerOpslaan.php',
    {
        password: 'pass',
        naam: naam,
        score: score
    })
      .then((response) => {
        dispatch({type: "SAVE_SCORE_SUCCESS", payload: response.data})
      })
      .catch((err) => {
        dispatch({type: "SAVE_SCORE_FAILURE", payload: err})
      })
  }
};

Why can't I do that? In the docs it clearly says it's possible. With $_POST it doesn't work either.


Source: (StackOverflow)

Vue JS AJAX call inside Modal

I am trying to have a modal pop up with details of a credit card. The details come from an AJAX request. For some reason the root Vue instance is updating but the component instance is not. This is what I currently have -

HTML:

<!-- View Card Details Modal -->
<!-- Modal -->
<div class="modal fade" id="ccdetails" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">View Card Details</h4>
      </div>
      <card-details cardid="{{$cc->card_id}}" :message="getCCDetails('{{$cc->card_id}}')"></card-details>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <!-- <button type="button" class="btn btn-primary">Save changes</button> -->
      </div>
    </div>
  </div>
</div>

Vue JS:

<script type="text/javascript">
Vue.component('card-details', {
  template: '<div class="modal-body">@{{message}}</div>',
  // data is technically a function, so Vue won't
  // complain, but we return the same object
  // reference for each component instance
 props: ['message', 'cardid']
}),
new Vue({
  el: '#ccdetails',
  data: {
    cardid: '',
    message: ''
  },
  methods: {
        getCCDetails: function (id) {
            console.log(id)
            console.log('calling function')
             axios.get('/card/'.concat(id))
                  .then(function (response) {
                    this.message = JSON.stringify(response.data)
                  }.bind(this))
                  .catch(function (error) {
                    return this.message = 'Sorry there was an error'
                  }.bind(this));
        }
  }
})
</script>

For the output, Root instance has cardid = undefined and message = the output I want. My cardDetails instance has the cardid value correct but message = undefined.


Source: (StackOverflow)

Axios spread() with unknown number of callback parameters

I need to process an unknown number of AJAX requests (1 or more) with axios, and I am not sure how to handle the response. I want something along the lines of:

let urlArray = [] // unknown # of urls (1 or more)

axios.all(urlArray)
.then(axios.spread(function () {
  let temp = [];
  for (let i = 0; i < arguments[i].length; i++)
    temp.push(arguments[i].data);
}));

where arguments will contain the callback responses sent by axios. The problem is that arguments contains the given string urls instead of the actual responses. How can I resolve this problem?


Source: (StackOverflow)

How to set state of response from axios in react

How do I set the state of a get response in axios?

axios.get(response){
    this.setState({events: response.data})
}

Source: (StackOverflow)

Axios can't set data

Here's my data:

data: function(){
    return {
        contas: [{id: 3,
            nome: "Conta de telefone",
            pago: false,
            valor: 55.99,
            vencimento: "22/08/2016"}] //debug test value
    };
},

And here's my get request:

beforeMount() {
    axios.get('http://127.0.0.1/api/bills')
        .then(function (response) {
            console.log("before: " + this.contas);
            this.contas = response.data;
            console.log("after: " + this.contas);
        });
},

The problem is I can't access this.contas from within axios.get(). I've tried Vue.set(this, 'contas', response.data); and window.listaPagarComponent.contas = response.data; without success.

My console shows:

before: undefined
after: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

But Vue Devtools shows only:

contas: Array[1]
  0: Object
    id: 3
    nome: "Conta de telefone"
    pago: false
    valor: 55.99
    vencimento: "22/08/2016"

Here's my full code.


Source: (StackOverflow)

Make Axios send cookies in its requests automatically

I am sending requests from the client to my Express.js server using Axios.

I set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand.

This is my clientside request example:

axios.get(`some api url`).then(response => ...

I tried to access headers or cookies by using these properties in my Express.js server:

req.headers
req.cookies

Neither of them contained any cookies. I am using cookie parser middleware:

app.use(cookieParser())

How do I make Axios send cookies in requests automatically?

Edit:

I set cookie on the client like this:

import cookieClient from 'react-cookie'

...
let cookie = cookieClient.load('cookie-name')
if(cookie === undefined){
      axios.get('path/to/my/cookie/api').then(response => {
        if(response.status == 200){
          cookieClient.save('cookie-name', response.data, {path:'/'})
        }
      })
    }
...

While it's also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set.


Source: (StackOverflow)

Axios interceptors and asynchronous login

I'm implementing token authentication in my web app. My access token expires every N minutes and than a refresh token is used to log in and get a new access token.

I use Axios for all my API calls. I have an interceptor set up to intercept 401 responses.

axios.interceptors.response.use(undefined, function (err) {
  if (err.status === 401 && err.config && !err.config.__isRetryRequest) {
    serviceRefreshLogin(
      getRefreshToken(),
      success => { setTokens(success.access_token, success.refresh_token) },
      error => { console.log('Refresh login error: ', error) }
    )
    err.config.__isRetryRequest = true
    err.config.headers.Authorization = 'Bearer ' + getAccessToken()
    return axios(err.config);
  }
  throw err
})

Basically, as I intercept a 401 response, I want to do a login and than retry the original rejected request with the new tokens. My serviceRefreshLogin function calls setAccessToken() in its then block. But the problem is that the then block happens later than the getAccessToken() in the interceptor, so the retry happens with the old expired credentials.

getAccessToken() and getRefreshToken() simply return the existing tokens stored in the browser (they manage localStorage, cookies, etc).

How would I go about ensuring statements do not execute until a promise returns?

(Here's a corresponding issue on github: https://github.com/mzabriskie/axios/issues/266)


Source: (StackOverflow)

How to use axios / AJAX with redux-thunk

Im using axios inside my action. I need to know if this is the right way to do it or not.

actions/index.js ==>

import axios from 'axios';
import types from './actionTypes'
const APY_KEY = '2925805fa0bcb3f3df21bb0451f0358f';
const API_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${APY_KEY}`;

export function FetchWeather(city) {
  let url = `${API_URL}&q=${city},in`;
  let promise = axios.get(url);

  return {
    type: types.FETCH_WEATHER,
    payload: promise
  };
}

reducer_weather.js ==>

import actionTypes from '../actions/actionTypes'
export default function ReducerWeather (state = null, action = null) {
  console.log('ReducerWeather ', action, new Date(Date.now()));

  switch (action.type) {
    case actionTypes.FETCH_WEATHER:
          return action.payload;
  }

  return state;
}

and then come combining them inside rootReducer.js ==>

import { combineReducers } from 'redux';
import reducerWeather from './reducers/reducer_weather';

export default combineReducers({
  reducerWeather
});

And finally calling it inside my React container some js file...

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {FetchWeather} from '../redux/actions';

class SearchBar extends Component {
  ...
  return (
    <div>
      ...
    </div>
  );
}
function mapDispatchToProps(dispatch) {
  //Whenever FetchWeather is called the result will be passed
  //to all reducers
  return bindActionCreators({fetchWeather: FetchWeather}, dispatch);
}

export default connect(null, mapDispatchToProps)(SearchBar);

Source: (StackOverflow)