D
D
Dmitry2017-04-09 22:10:14
JavaScript
Dmitry, 2017-04-09 22:10:14

How to correctly initialize default settings for one of the modules in the project?

There are n-number of modules, one for each page of the application.
Example:
- user-profile.js
- catalog.js
- conversations.js
- login.js
Each page uses the Axios module as a wrapper for XMLHttpRequest .
To correctly recognize an AJAX request on the backend, you have to write a default config for this module:

axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
};

In what one place to register this config and how then in each of the modules to reuse this functionality?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2017-04-09
@another_dream

Specify it at the very beginning (that is, at the "top" of the application, where it "appears" for the first time), where axios is applied / or somewhere you import it for this. Wouldn't that work?
Or this option:

function buildHeaders() {
  const authToken = localStorage.getItem('token')
  return { ...defaultHeaders, Authorization: authToken }
}

export function httpGet(url) { //экспортируете функцию для будущих вызовов
  return fetch(url, { // я использую fetch, но для axios сделать, думаю вы сможете
    headers: buildHeaders(), // те самые заголовки, которые нужны в каждом запросе
  })
  .then(checkStatus) // это уже не важно, у меня в коде просто далее идет еще несколько проверок общих
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question