Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding what does Axios create do

I was asked to make API call to send data.

On Click in vue, I was firing this event

async facebookDataToSend () {
  let campaignID = await this.$store.getters['CurrentInstance/id']
  this.$axios.post(process.env.API_BASE_URL + 'faceeBookCampaign', { campaignID: campaignID }, { withCredentials: true })
},

But then, I was told to use API functions which already exsist in some xyz.js file.

My xyz.js file looks like this..

const rest = {
  something: axios.create({
    baseURL: process.env.API_BASE_URL,
    withCredentials: true
  }),
  setClient: function (client) {
    this.something = axios.create({
      baseURL: process.env.API_BASE_URL,
      withCredentials: true,
      params: {
        __somethingClient: client
      }
    })
    this.client = client
  }
}

Here, I am unable to comprehend how can I use this instance to make an api call So I viewed the code where they have already made the api call and saw something like this

const API = {
  url: '/whateverHtml/',
        method: 'post',
        withCredentials: true,
        data: {
          'schemaType': 'something-event', // TODO FIXME
          'field': 'description', // TODO FIXME
          'html': this.model[this.field.key]
        }
api.something.request(API).then(result => {

And I wasn't able to comprehend the code. For starters

What is request? I don't see my any method or property inside something in my rest variable

second why are they using withCredentials: true in their API object when they have already set up the property as true in rest object]

What are the pro's of using axios.create({ i.e what they are doing than what I initially did this.$axios.post(

like image 437
anny123 Avatar asked Mar 04 '19 01:03

anny123


People also ask

What is the use of Axios NPM?

It is used to provide an easy-to-use JSON database that can be used to answer HTTP queries. The HTTP client we'll use to send HTTP queries to the JSON server is called Axios. The above code installs the server. Now create a test JSON data called user.

What does Axios do and how does it work?

Axios works by making HTTP requests with NodeJS and XMLHttpRequests on the browser. If the request was successful, you will receive a response with the data requested. If the request failed, you will get an error. You can also intercept the requests and responses and transform or modify them.

What does Axios do in JavaScript?

Axios is a promised-based HTTP client for JavaScript. It has the ability to make HTTP requests from the browser and handle the transformation of request and response data.

What function can you call to create a new instance of Axios with a custom configuration?

In this example, we are using axios. create() to create a new instance of Axios with a custom configuration that has a base URL of http://localhost:3002/products and a timeout of 1000 milliseconds. The configuration also has an Accept and Authorization headers set depending on the API being invoked.


1 Answers

request is a method defined by axios. Link to docs.

request allows you to make an HTTP call with any verb you want (POST, GET, DELETE, PUT). Most likely axios calls request from inside all the other helper methods (get, post), but this is an implementation details. One of the advantages of using request is that you don't have to hardcode the HTTP verb (POST, GET ...) and you can set it at run time depending on your input.

I see 2 reasons why they would set withCredentials:

  • setClient may or may not be called before something
  • for clarity: it's enough to look at the definition of something to realise that the client is using credentials and you don't need any extra information about how rest works.

I don't think the request for you to use something boils down to advantages of axios.$post vs axios.create. It's probably related more to how to organise your code.

Some advantages of using a separate module vs calling axios directly

  • when calling axios directly you are prepending base url all the time, when using a module for your REST API the base URL is tucked away and arguably makes your code easier to read
  • you can bake other options inside config and make sure they are used. For instance you may have an access token, the module can store that token and always added to any request. When calling axios by hand you need to remember this
  • you are decoupled from axios (to some degree)(1). When using a module you don't actually care if it's axios doing the requests or not.
  • You can add more API calls to the module that you can reuse in the future. I'm expecting xyz file to grow in time and your call to faceeBookCampaign to end up being a method on the rest variable. It makes more sense to end up using this.client and not something but this is up to the devs.
  • it keeps all the REST API calls in one place allowing you to build an SDK for that API, which as the project grows can have its own life cycle.

(1) I say that id decouples you to some degree because there are semantics that need to be kept so everything works. The returned object needs to have a request method that accepts a config object. The config need to conform to the same structure as the one that axios wants. But, you can always write an adapter for that, so you are actually decoupled from axios.

like image 71
Radu Diță Avatar answered Oct 18 '22 00:10

Radu Diță