Client http per Javascript.
$ npm install axios
Amb node.js:
var axios = require('axios') axios.get('https://api.github.com/users/codeheaven-io');
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Són similars als Middleware de Laravel
Exemple d'ús amb Laravel (és compatible amb vue-resource excepte configuració interceptors):
const app = new Vue({ el: '#app', data: { todos: [] }, methods: { fetchData: function() { // GET /someUrl this.$http.get('/api/v1/task').then((response) => { this.todos = response.data.data; }, (response) => { // error callback sweetAlert("Oops...", "Something went wrong!", "error"); console.log(response); }); } }, created: function() { console.log('Component created!'); this.fetchData() } });
Per tal que funcioni la variable http cal canviar la configuració de Laravel al fitxer bootstrap.js:
window.Vue = require('vue'); // require('vue-resource'); window.axios = require('axios'); Vue.prototype.$http = axios; require('sweetalert'); /** * We'll register a HTTP interceptor to attach the "CSRF" header to each of * the outgoing requests issued by this application. The CSRF middleware * included with Laravel will automatically verify the header's value. */ //Vue.http.interceptors.push((request, next) => { // request.headers['X-CSRF-TOKEN'] = Laravel.csrfToken; // // next(); //}); axios.defaults.headers.common['X-CSRF-TOKEN'] = Laravel.csrfToken;
NOTA: Observeu com definim el Token CSRF però tinc dubte si el sistema que ja porta axios podria servir?
Vegeu com utilitzem SweetAlert per mostrar els errors.
Vue-resource ja no és més un paquet oficial (tot i que es pot continuar utilitzant):