EzDev.org

axios

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


How to download files using axios

I am using axios for basic http requests like get and post, and it works well. Now I need to be able to download excel files too. Is this possible with axios. If so does anyone have some sample code? If not what else can I use in a react application to do the same?


Source: (StackOverflow)

Using Axios GET with Authorization Header in React-Native App

Sorry if this is a noob question, but I'm trying to use axios for a get request with an API which requires an Authorization header

My current code:

const AuthStr = 'Bearer ' + USER_TOKEN;

//where USER_TOKEN is the access_token needed. This string concatenation may be the issue as if I post this as AuthStr = 'Bearer 41839y750138-391', the following GET request works and returns the data im after!)

axios.get(URL, { 'headers': { 'Authorization': AuthStr } })
.then((response => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});

I also tried setting this as a global header with no success :(

ANY HELP WOULD BE GREATLY APPRECIATED!


Source: (StackOverflow)

How can I get the status code from an http error in Axios?

This may seem stupid, but I'm trying to get the error data when a request fails in Axios.

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log(error) //Logs a string: Error: Request failed with status code 404
    })

Instead of the string, is it possible to get an object with perhaps the status code and content? For example:

Object = {status: 404, reason: 'Not found', body: '404 Not found'}

Source: (StackOverflow)

How do I set multipart in axios with react?

When I curl something, it works fine:

curl -L -i -H 'x-device-id: abc' -F "url=http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"  http://example.com/upload

How do I get this to work right with axios? I'm using react if that matters:

uploadURL (url) {
  return axios.post({
    url: 'http://example.com/upload',
    data: {
      url: url
    },
    headers: {
      'x-device-id': 'stuff',
      'Content-Type': 'multipart/form-data'
    }
  })
  .then((response) => response.data)
}

This doesn't work for some reason.


Source: (StackOverflow)

Axios Http client - How to construct Http Post url with form params

I am trying to create a postHTTP request with some form parameters that are to be set. I am using the axios with node server. I already have a java code implementation of constructing a url as given below:

JAVA CODE:

HttpPost post = new HttpPost(UriBuilder.fromUri (getProperty("authServerUrl"))
            .path(TOKEN_ACCESS_PATH).build(getProperty("realm")));

List<NameValuePair> formParams = new ArrayList<NameValuePair>();

formParams.add(new NameValuePair("username",getProperty ("username")));
formParams.add(new NameValuePair("password",getProperty ("password")));
formParams.add(new NameValuePair("client_id, "user-client"));

I am trying to do the same thing in axios.

AXIOS IMPLEMENTATION:

axios.post(authServerUrl +token_access_path,
        {
                username: 'abcd', //gave the values directly for testing
                password: '1235!',
                client_id: 'user-client'
        }).then(function(response) {
            console.log(response); //no output rendered
        }

Is the approach to set these form params on the post request correct?


Source: (StackOverflow)

Axios get access to response header fields

I'm building a frontend app with React and Redux and I'm using axios to perform my requests. I would like to get access to all the fields in the header of the response. In my browser I can inspect the header and I can see that all the fields that I need are present(such as token, uid, etc...), but when I call

const request = axios.post(`${ROOT_URL}/auth/sign_in`, props);
request.then((response)=>{
  console.log(response.headers);
});

I get just

Object {content-type: "application/json; charset=utf-8", cache-control: "max-age=0, private, must-revalidate"}

Here my browser network tab,as you can see all the other fields are present.

enter image description here

Bests.


Source: (StackOverflow)

How to catch and handle error response 422 with Redux/Axios?

I have an action making a POST request to the server in order to update a user's password, but I'm unable to handle the error in the chained catch block.

return axios({
  method: 'post',
  data: {
    password: currentPassword,
    new_password: newPassword
  },
  url: `path/to/endpoint`
})
.then(response => {
  dispatch(PasswordUpdateSuccess(response))
})
.catch(error => {
  console.log('ERROR', error)
  switch (error.type) {
    case 'password_invalid':
      dispatch(PasswordUpdateFailure('Incorrect current password'))
      break
    case 'invalid_attributes':
      dispatch(PasswordUpdateFailure('Fields must not be blank'))
      break
  }
})

When I log the error this is what I see:

Error Logged

When I check the network tab I can see the response body, but for some reason I can't access the values!

Network Tab

Have I unknowingly made a mistake somewhere? Because I'm handling other errors from different request fine, but can't seem to work this one out.


Source: (StackOverflow)

axios: https request over proxy

I am trying to use axios with a proxy server to make an https call:

const url = "https://walmart.com/ip/50676589"
var config = { proxy: { host: proxy.ip, port: proxy.port } }

axios.get(url, config)
.then(result => {})
.catch(error => {console.log(error)})

The proxy servers I am using are all in the United States, highly anonymous, with support for HTTP and HTTPS.

I am receiving this error:

{ Error: write EPROTO 140736580649920:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:794:

In order to ensure that the problem is with axios and NOT the proxy, I tried this:

curl -x 52.8.172.72:4444 -L 'https://www.walmart.com/ip/50676589'

This totally works just fine.

How do I configure axios to work with proxies and https URL's?


Source: (StackOverflow)

Handle status (e.g. 503) in Axios OPTIONS response

edit2: https://stackoverflow.com/a/37784969/107282 suggests that I needn't worry because it doesn't happen when on a real device.


I'm using Axios in a VueJS hybrid (Cordova) app and am calling an API.

Axios is (correctly) doing a 'preflight' OPTIONS request before my GET/POST requests, but if the API returns a 503 at that point, my error handling code doesn't get called.

HTTP.post(url, data, {headers: {Authorization: 'Bearer ' + token.getAccessToken()}})
  .then(response => response)
  .catch(error => {
    // Not reached
  });

How do I catch this error status?


edit: screenshot from chrome dev tools:

503 on OPTIONS request


Source: (StackOverflow)

How to send Basic Auth with axios

im trying to implement the following code but something is not working. Here is the code:

  var session_url = 'http://api_address/api/session_endpoint'
  var username = 'user';
  var password = 'password';
  var credentials = btoa(username + ':' + password);
  var BasicAuth = 'Basic ' + credentials;
  axios.post(sesion_url,{
    headers: {'Authorization': +BasicAuth}
  }).then(function(response){
    console.log('Authenticated');
  })
  .catch(function (error){
    console.log('Error on Authentication');
  });

Its returning a 401 Error. When I do it with Postman there is an option to set Basic Auth if I dont fill those fields it also returns 401 but if I do the request its successfull.

Any ideas what im doing wrong?

Here is part of the docs of the API of how to implement this: This service uses Basic Authentication information in the header to establish a user session. Credentials are validated against the Server. Using this web-service will create a session with the user credentials passed and return a JSESSIONID. This JSESSIONID can be used in the subsequent requests to make web-service calls.


Source: (StackOverflow)

Attach Authorization header for all axios requests

I have a react/redux application that fetches a token from an api server. After the user authenticates I'd like to make all axios requests have that token as an Authorization header without having to manually attach it to every request in the action. I'm fairly new to react/redux and am not sure on the best approach and am not finding any quality hits on google.

Here is my redux setup:

// actions.js
import axios from 'axios';

export function loginUser(props) {
  const url = `https://api.mydomain.com/login/`;
  const { email, password } = props;
  const request = axios.post(url, { email, password });

  return {
    type: LOGIN_USER,
    payload: request
  };
}

export function fetchPages() {
  /* here is where I'd like the header to be attached automatically if the user
     has logged in */ 
  const request = axios.get(PAGES_URL);

  return {
    type: FETCH_PAGES,
    payload: request
  };
}

// reducers.js
const initialState = {
  isAuthenticated: false,
  token: null
};

export default (state = initialState, action) => {
  switch(action.type) {
    case LOGIN_USER:
      // here is where I believe I should be attaching the header to all axios requests.
      return {
        token: action.payload.data.key,
        isAuthenticated: true
      };
    case LOGOUT_USER:
      // i would remove the header from all axios requests here.
      return initialState;
    default:
      return state;
  }
}

My token is stored in redux store under state.session.token.

I'm a bit lost on how to proceed. I've tried making an axios instance in a file in my root directory and update/import that instead of from node_modules but it's not attaching the header when the state changes. Any feedback/ideas are much appreciated, thanks.


Source: (StackOverflow)

Node.js HTTP GET “ECONNRESET” Error on read

I've read all the related issues on SO and GitHub about this error and none of them seem to address this situation.

When I run the following code:

response = await axios.get('http://localhost:8082/panda, {
  httpAgent: new http.Agent({ keepAlive: true, keepAliveMsecs: 10000 })
});

I get the following error:

{ Error: socket hang up
    at createHangUpError (_http_client.js:345:15)
    at Socket.socketOnEnd (_http_client.js:437:23)
    at emitNone (events.js:110:20)
    at Socket.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1059:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9) code: 'ECONNRESET' }
{ Error: read ECONNRESET
    at _errnoException (util.js:1019:11)
    at TCP.onread (net.js:608:25)
  code: 'ECONNRESET',
  errno: 'ECONNRESET',
  syscall: 'read',
  etc...

There's no stack trace beyond the onread call so it's unclear how I can get any additional information beyond the ECONNRESET error code (-54) passed to the onread method in net.js

This issue happens with every request - it is not intermittent.

A few observations:

  • when making the same request from chrome or postman the request does NOT fail
  • attempting to reproduce a successful request from Chrome, by using the same headers, fails
  • setting the accept header to use 'gzip', etc.. does not help - I have tried all the recommendations including some weird ones like setting the content length and adding a body to the request despite this being a GET request
    • the error always appears in net.js, but happens with both the request and axios libraries

Here's the interesting part - I can only seem to reproduce this problem reliably when I am hosting the server locally. I am able to reach the dev instance or run the server in vagrant, via a docker container, without issue.

I am running macOS Sierra 10.12.6 if that makes any difference. The server is written in Java and uses the Spring framework. Here is the RestTemplate configuration I'm using for HTTP calls:

@Bean
public RestTemplate restTemplate() {
    //request timeout
    int timeout = 5000;

    //Connection Pooling factory with timeouts to prevent disastrous request responses
    HttpComponentsClientHttpRequestFactory cf = new HttpComponentsClientHttpRequestFactory();
    cf.setReadTimeout(timeout);
    cf.setConnectTimeout(timeout);
    cf.setConnectionRequestTimeout(timeout);

    return new RestTemplate(cf);
}

I've tried messing around with these settings with no luck.

Any ideas?


Source: (StackOverflow)

Axios (in React-native) not calling server in localhost

I'm building a really easy api and react-native application. The server works well (tested with PostMan) but the application doesn't call the server. It blocks when axios has to send the post request (see below).

I'm desperate :-( Loosing too mush time in it. Please, if you can help me...

Here is my code LogIn page. It dispatch the action creator (working with redux) giving email and password:

...
const LogIn = React.createClass({
  submitLogin() {
    // log in the server
    if (this.props.email !== '' && this.props.psw !== '') {
      if (this.props.valid === true) {
        this.props.dispatch(logIn(this.props.email, this.props.psw));
      } else {
        this.props.dispatch(errorTyping());
      }
    }
  },
...

email and password are weel retrieved and sent to the action creator:

import axios from 'axios';
import { SIGNIN_URL, SIGNUP_URL } from '../api';
// import { addAlert } from './alerts';
exports.logIn = (email, password) => {
  return function (dispatch) {    
    console.log(email);
    console.log(password);
    console.log(SIGNIN_URL);
    return axios.post(SIGNIN_URL, { email, password })
    .then(
      (response) => {
        console.log(response);
        const { token, userId } = response.data;
        dispatch(authUser(userId));
      }
    )
    .catch(
      (error) => {
        console.log('Could not log in');
      }
    );
  };
};
const authUser = (userId) => {
 return {
 type: 'AUTH_USER',
 userId
 };
};
...

The three console.log() before axios show the data in the correct way. SIGNIN_URL is exactly the same I use in postman. ...but axios doesn't call.

Just to give all the cards, this is my store:

import thunk from 'redux-thunk';
import { createStore, compose, applyMiddleware } from 'redux';
import { AsyncStorage } from 'react-native';
import { persistStore, autoRehydrate } from 'redux-persist';
import reducer from '../reducer';
const defaultState = {};
exports.configureStore = (initialState = defaultState) => {
 const store = createStore(reducer, initialState, compose(
 applyMiddleware(thunk),
 autoRehydrate()
 ));
 persistStore(store, { storage: AsyncStorage });
 return store;
};

There's no error message in the debugger (but the one given by the axios call ('Could not log in')

I'm on windows 10, with:

"axios": "^0.15.3",
"react": "15.4.2",
"react-native": "0.38.0",
"redux": "^3.6.0"

The call fails even when I prepare a simple GET call and the server is supposed to give back a simple message (tested with postman and browser):

exports.test = () => {
  return function () {
    return axios.get('https://localhost:3000/v1/test')
    .then(
      (response) => {
        console.log(response);
      }
    )
    .catch(
      (error) => {
        console.log('error');
      }
    );
  };
};

Last, I tryed also to modify the call adding a header as the following, because the api is coded to accept json:

const head = {
  headers: { 'Content-Type': 'application/json' }
};

exports.test = () => {
  return function () {
    return axios.get('https://api.github.com/users/massimopibiri', head)
    .then(
      (response) => {
        console.log(response);
      }
    )
    .catch(
      (error) => {
        console.log('error');
      }
    );
  };
};

but even this didn't work. hope somebody can help me. Other similar issues didn't.


Source: (StackOverflow)

Force download GET request using axios

I'm using vuejs 2 + axios. I need to send a get request, pass some params to server, and get a PDF as a response. Server uses Laravel.

So

axios.get(`order-results/${id}/export-pdf`, { params: { ... }})

makes successful request but it does not start force downloading, even though server returns correct headers.

I think this is a typical situation when you need to, say, form a PDF report and pass some filters to server. So how could it be accomplished?

Update

So actually I found a solution. However the same approach didn't work with axios, don't know why, that's why I used raw XHR object. So the solution is to create a blob object and user createUrlObject function. Sample example:

let xhr = new XMLHttpRequest()
xhr.open('POST', Vue.config.baseUrl + `order-results/${id}/export-pdf`, true)
xhr.setRequestHeader("Authorization", 'Bearer ' + this.token())
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhr.responseType = 'arraybuffer'

xhr.onload = function(e) {
  if (this.status === 200) {
    let blob = new Blob([this.response], { type:"application/pdf" })
    let link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = 'Results.pdf'
    link.click()
  }
}

Important: you should have array buffer as response type

However, the same code written in axios returns PDF which is empty:

axios.post(`order-results/${id}/export-pdf`, {
  data,
  responseType: 'arraybuffer'
}).then((response) => {
  console.log(response)

  let blob = new Blob([response.data], { type: 'application/pdf' } ),
      url = window.URL.createObjectURL(blob)

  window.open(url); // Mostly the same, I was just experimenting with different approaches, tried link.click, iframe and other solutions
})

Source: (StackOverflow)

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)