Axios instance does not return in nodejs export

Asked

Viewed 167 times

1

I’m trying to return the instance created through the module.exports, but when I try to use it it gives me that mistake:

http(...). get is not a Function

My http-common.js file

var axios = require('axios');

var instancia = axios.create({
    baseURL: `http://jsonplaceholder.typicode.com/`,
});

module.exports = instancia;

My index.js

var http = require('./app/infraestrutura/http-common')();
http.get('/users')
        .then(function(response){
            console.log(response)
        }).
        catch(function(err){
            console.log(response)
        })
  • Remove the require parentheses on require('./app/infraestrutura/http-common')(). Should be require('./app/infraestrutura/http-common')

  • @user140828 worked, but not as I wanted, the idea was it just run the request, when I called the method .get() or .post()

  • 1

    But that’s exactly what’s happening. What you call the method get immediately after importing the module, he makes the request right away. If you wanted to call this request later, maybe it is the case to put it inside a function and call this function only when necessary.

  • @user140828 is you are right, the best way to do this is to export the very instance of Axios and set the baseURL ( through Axios.defaults ) before exporting there

1 answer

1


The solution was to export the entire Axios instance itself, and make modifications before exporting it:

var axios = require('axios');
axios.defaults.baseURL = 'http://jsonplaceholder.typicode.com/';

module.exports = axios;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.