About Framework7-vue-cli Ajax Interceptor - ajax

I want to intercept all ajax requests with a status code of -1 in all response and redirect it to the login screen. But I have been unable to monitor it. What should I do? Thank you.
My method:
app.js
Framework7.Dom7(document).on('ajaxComplete', function(e){
console.log('Monitored')
})

Try this.
Create a new file name interceptors.js
interceptors.js
import axios from 'axios';
import Vue from 'vue'
export default function setup() {
axios.interceptors.response.use(function (config) {
// Do something before the request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
}
then in your app.js import the interceptors.js
app.js
import interceptorsSetup from './interceptors';
interceptorsSetup()

Related

Laravel Vue3 - Passing Token and User info to Vue store

I'm creating a Laravel/Vue3 app and wanted to completely separate the Laravel router from the SPA router.
In order to achieve this I created a dashboard.blade.php file which contains the following content:
<x-app-layout>
<div id="app"></div>
</x-app-layout>
Vue then simply mounts on top of that div and the app is started.
My webpack.mix.js:
const mix = require("laravel-mix");
mix.ts("resources/js/app.ts", "public/js")
.vue({ version: 3 })
.postCss("resources/css/app.css", "public/css", [
require("postcss-import"),
require("tailwindcss"),
require("autoprefixer"),
]);
The app.ts file is also quite simple:
import { createApp } from 'vue';
import App from './App';
createApp(App).mount('#app');
Which is great, but my holdup is that for subsequent requests (via Axios), I will need the user token. How can I get this token/logged in user info to my Vue3 app?
I'm using Laravel Breeze for authentication (if that helps).
Thank you,
It turns out the answer was 'extremely' simple. I had to do nothing besides removing the comment tags on this line:
And add headers as follows in your axios config:
import axios from "axios";
import store from "../store";
const Axios = axios.create({
baseURL: process.env.APP_URL,
headers: { Accept: "application/json" },
});
Axios.interceptors.request.use(
(config) => {
store.commit("setLoader", true);
return config;
},
(error) => Promise.reject(error)
);
Axios.interceptors.response.use(
(response) => {
store.commit("setLoader", false);
return response;
},
(error) => Promise.reject(error)
);
export default Axios;
Subsequent axios calls have the token attached automatically.
You can find all the required information here. Love Laravel...

Vue.js interceptors not working and nothing return

I have problem with axios interceptors. I try set header for jwt using interceptors but nothing work so I changed my code and added only console.log to this code. When I open console in Chrome nothing is displayed. Do you have any idea what the problem could be?
import axios from 'axios'
const baseURL = 'http://localhost:8080'
const instance = axios.create({
baseURL,
params: {}
})
instance.interceptors.request.use(function (config) {
console.log('test');
return config;
}, function (error) {
return Promise.reject(error)
})
export default instance
I just took a look into an old project that I used interceptors. There I called it directly on the axios object.
Perhaps something like the code bellow will work.
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:8080';
axios.interceptors.request.use(function (config) {
console.log('config', config);
return config;
}, function (error) {
return Promise.reject(error)
});
export default instance;

Axios response.data return HTML instead of an object

I need help about Axios.
I develop a SPA webapp on Laravel 6 (with package SPARK) and VueJS (version 2).
On a Vue component, I want to retrieve datas from my bdd.
So, I use Axios to make a get request on an API uri.
But, when I call Axios request, data field in Response object is a HTML code.
This is my code :
routes/web.php
Route::get('/', function(){
return view('welcome');
});
Route::middleware('auth')->get('/{any?}', function (){
return view('documents');
})->where('any', '[\/\w\.-]*');
The "welcome" view is a blade page where redirect on "/login" if user is not authenticate.
Otherwise, it redirect on "/home".
The link "/home" is define on vue-router in app.js.
The other route is the unique way to display the webapp (it's a single page application).
The Vue instanciation is in "passeport" view.
resources/js/app.js
import 'es6-promise/auto'
require('spark-bootstrap');
require('./components/bootstrap');
window.Vue = require('vue');
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios, axios);
Vue.component('index', require('./components/pages/index').default);
import Dashboard from './components/pages/dashboard.vue';
...
const routes = [
{
name: 'dashboard',
path: '/home',
component: Dashboard,
},
{...}
]
const router = new VueRouter({
history: true,
mode: 'history',
routes: routes
});
var app = new Vue({
mixins: [require('spark')],
router,
});
router package is added in Vue instanciation.
it is in the same context than spark component (identify by the #spark-app element)
resources/views/documents.blade.php
#extends('spark::layouts.app')
#section('content')
<div id="app">
<index :user="user"></index>
</div>
#endsection
It is the view returned for any path.
In the spark::layout.app, there is only a div with id="spark-app" and the #yield('content').
resouces/js/components/pages/index.vue
<template>
<transition name="fade">
<Component :is="layout" :user="user">
<router-view :layout.sync="layout" :user="user"></router-view>
</Component>
</transition>
</template>
.
.
<script>
const default_layout = "default";
export default{
props: ['user'],
data(){
return{
layout: 'div',
}
},
}
</script>
It's just the vue component with the router-view configure with a layout.
resources/js/components/pages/dashboard.vue
<template>
...
</template>
<script>
import Default from './../layouts/Default.vue'
export default {
props: ['user'],
data: function () {
return {
documents: []
}
},
created() {
this.$emit('update:layout', Default);
},
mounted(){
// extract passeports's informations
this.axios.get('/api/documentslist').then(response => {
console.log(response);
this.documents= response.data.data;
});
}
}
</script>
Here, I call the documentslist API define in routes/api.php.
routes/api.php
Route::middleware('auth:api')->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
Route::get('/documentslist', 'DocumentController#list');
});
app/http/Controllers/DocumentController.php
...
public function list(Request $request){
return DocumentCollection(Document::all());
}
...
When I go to "/home", I verified "documents" data in Vue (or in the javascript console log), and response.data = "\r\n\r\n\r\n (...) v-if=\"notification.creator\" :src=\"notification.creator.photo_url\" class=... (10024 total length)"
But, list method in DocumentController have to return a list of documents, and not a HTML code.
Furthermore, I use Passport Laravel to unified authentication by login and the API token.
And the Axios request work in the same project without SPA structure.
I hope I'm clear in the problem explanation, and that I forget any detail to understand.
Thanks.
You can simply return like this from your controller
return response()->json(Document::all());
I suspect the API link to redirect with the SPA route (in routes/web.php, any path return the "home" view).
I try to change route in routes/web.php.
instead of :
Route::middleware('auth')->get('/{any?}', function (){
return view('home');
})->where('any', '[\/\w\.-]*');
I put this :
Route::middleware('auth')->get('/home', function (){
return view('home');
});
Like this, this route doesn't take account of all path.
And...it works !
But...it isn't what I want :(
Indeed, without the route with '/{any?}' the SPA doesn't work.
I don't understand why this method works another project in Laravel (without Spark package), and doesn't work with this project.
I don't know about laravel but this problem arises when the route you are calling is not the correct one. Do some efforts and check what route the application in eventually calling also take a look at your proxy settings.
****I am NodeJs developer not Laravel

The difference between axios and this.$axios

I am developing using nuxt and gridsome.
These are all vue frameworks and I found that there are something interesting.
When I do like this:
<script>
import axios from 'axios';
...
created: function created() {
axios.get(process.env.NUXT_ENV_API_URL + '/users').then(res=>{
this.options=res.data.map(function(data){
return {name: data.url, provider_id: data.provider_id};
});
}
I got 401 error(backend is laravel).
message: "Unauthenticated."
But when I use this, it's working.
<script>
import axios from 'axios';
...
created: function created() {
this.$axios.get(process.env.NUXT_ENV_API_URL + '/users').then(res=>{
this.options=res.data.map(function(data){
return {name: data.url, provider_id: data.provider_id};
});
}
It's because Axios allows to create instances of itself which you can therefore customize. So when you do axios.get, underlying, Axios creates an instance on the fly before using it. When you do this.$axios.get, you use an already created instance which got customized somewhere else in your code (by adding some HTTP headers for example)

Vue.js Google / Microsoftgraph login

I have a Laravel app and I am using vue.js and vue-authenticate to have a user login with their Microsoft account. The vue.js app is living under a laravel route not Laravel home page i.e. if the homepage route is / then the vueapp route is /vueapp.
On the vueapp's home page I have the Login with Microsoft button configured. In my vue app the base url is set to mydomain/vueapp. I can successfully authorize the app with my Microsoft account but then instead of being able to see a success message and a token, I see the following error:
Error: Request failed with status code 405
I have Axios and Vuex installed and my vue routes are supported in the hash mode instead of history because of some weird laravel issue.
Update: I am seeing a similar issue with Google. It seems like something happens when the URI is redirected.
Update: Below is my code:
For my component:
<script>
import store from '../store'
import axios from 'axios'
export default{
data () {
return {
}
},
methods: {
authenticate: function (provider) {
console.log("Login Started" + provider);
this.$auth.authenticate(provider).then((response) => {
console.log("Login Successful " + response);
}).catch(error => {
console.log("error occured ");
console.log(error);
})
}
},
}
</script>
My HTML ---
auth Live
auth Google
In my app.js
import Vue from 'vue'
import lodash from 'lodash'
import VueLodash from 'vue-lodash'
import VueAxios from 'vue-axios'
import VueAuthenticate from 'vue-authenticate'
import Vuex from 'vuex'
import App from './App.vue'
import router from './router'
import axios from 'axios'
Vue.use(VueLodash, lodash)
Vue.use(require('vue-moment'));
import vmodal from 'vue-js-modal'
Vue.use(vmodal, {
dialog: true,
dynamic: true,
})
import Toasted from 'vue-toasted';
Vue.use(Toasted, 'top-center')
Vue.use(VueAxios, axios)
Vue.use(Vuex)
import VueAuthenticate from 'vue-authenticate'
Vue.use(VueAuthenticate, {
baseUrl: 'https://www.mywebsite.com', // Your API domain
providers: {
live: {
clientId: 'My Mcirosoft key',
redirectUri: 'https://www.mywebsite.com/auth/live' // Your client app URL
},
google: {
clientId: 'mygooglekey.apps.googleusercontent.com',
redirectUri: 'https://www.mywebsite.com/auth/google'
}
}
})
In laravel - I have the following routes. Webapp is the folder where vue app lives and it uses the hash mode for routing not history.
Route::get('webapp/{path?}', function () {
return View::make('app');
})->where( 'path', '([A-z\d-\/_.]+)?' );
Route::get('auth/live', function () {
return View::make('app');
});
Route::get('auth/google', function () {
return View::make('app');
});

Resources