Skip to content

Instantly share code, notes, and snippets.

@philipboomy
Forked from carlcs/axios.js
Created March 22, 2019 15:43
Show Gist options
  • Save philipboomy/116e680e0fb7feece4833b09e7a9d7e8 to your computer and use it in GitHub Desktop.
Save philipboomy/116e680e0fb7feece4833b09e7a9d7e8 to your computer and use it in GitHub Desktop.
import qs from 'qs';
import Axios from 'axios';
Axios.defaults.baseURL = Craft.baseUrl;
Axios.defaults.headers.common['Accept'] = 'application/json';
Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Axios.interceptors.request.use(config => {
if (config.data instanceof FormData) {
config.data.append(Craft.csrfTokenName, Craft.csrfToken);
} else if (config.data === Object(config.data)) {
config.data = qs.stringify(Object.assign({[Craft.csrfTokenName]: Craft.csrfToken}, config.data));
}
return config;
});
window.axios = Axios;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Axios with Craft</title>
<link rel="stylesheet" href="{{ alias('@web/assets/app.css') }}">
<script src="{{ alias('@web/assets/vendor.js') }}" defer></script>
<script src="{{ alias('@web/assets/app.js') }}" defer></script>
{% set jsCraft = {
baseUrl: alias('@web'),
csrfTokenName: craft.app.config.general.csrfTokenName,
csrfToken: craft.app.request.csrfToken,
} %}
<script>window.Craft = {{ jsCraft|json_encode|raw }}</script>
</head>
<body>
<div id="app">
{% block layout %}
{% endblock %}
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment