Answer the question
In order to leave comments, you need to log in
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'
};
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question