vue3 App.vue mounted not running first before a compoment View being created - axios

I created FunA in App.vue Mounted(). I created FunB in HomeView.vue Mounted().
I go to HomeView Page and Refresh the page, FunB run before FunA.
My Question is isn't App.vue Stuff run first before the compoment stuff ? I created FunC in App.vue beforeCreate(), and go back HomeView page and refresh again. I saw that Fun B still run before FunC and FunA.
If I am using FunA as a global function to setup Axios Auth Headers, all compoment Mounted functions with Axios get will return 403 error.
All stuff is working correctly if I enter the view by router-view.
What should I do except adding the auth headers to all Axios Request.
App.vue
async mounted() {
await this.getServerTokenAuth()
},
methods: {
async getServerTokenAuth(){
await this.$mainApi.post('api/auth/', {
"username": "qweqwe",
"password": "qweqweqwe"
})
.then(response => {
console.log(response.data.token)
this.$store.commit("setServerToken")
this.$mainApi.defaults.headers.common['Authorization'] = "Token " + response.data.token;
this.$mainApi.defaults.headers.common['Accept-Language'] = this.$store.state.language;
if(this.$store.state.isAuthenticated === true){
this.$mainApi.defaults.headers.common['CUSTOM_HEADERS'] = "qweqweqwe";
console.log("User Data Added to Headers")
}
})
},
HomeView
async mounted() {
await this.getBackendData() // return 403 error
},
methods: {
async getBackendData(){
// try to console log the Auth Headers, return undefined
await this.$mainApi.get('api/product/list/')
.then(response => {
if(response.data.status === 80){
this.tabulator.setData(response.data.details)
this.totalProduct = response.data.details.length
}
})
}
},

I think using AwaitLock is a solution in this case. The HomeView mounted hook will be locked until the App mounted hook is done.

I found the method to solve.
How to use async/await in vue lifecycle hooks with vuex?
Just Add a flag in App.vue's api Function.
async getServerTokenAuth(){
await this.$mainApi.post('api/auth/', {
"username": "qweqwe",
"password": "qweqwe"
})
.then(response => {
...
this.doneApiSetting = true // ADD THIS
In App.vue Template
<template>
// Add a Flag here, so this part will run after the API setting is complete
<div class="main" v-if="doneApiSetting">
<router-view/>
</div>
</template>

Related

How can I attach my JWT token to every axios call?

I'm working on my very first nextjs application. I'm using an axios instance to handle my calls to backend
export const httpClient = axios.create({
baseURL: `${process.env.BASE_URL}`,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
I'm also using next-auth to handle my authentication and authorization
const callbacks = {
async jwt(token, user) {
if (user) {
token.accessToken = user.access_token;
}
return token;
},
async session(session, token) {
session.accessToken = token.accessToken;
return session;
},
};
The call to the authentication endpoint is working correctly. If I console.log() the api response I can see the returned JWT token.
I'm now trying to attach that JWT token to every axios request but the call await getSession() is always null. I wrote following request interceptor
httpClient.interceptors.request.use(
async (config) => {
const session = await getSession();
if (session) { // this never evaluates to true. Session is always `null`
console.log(session);
config.headers.Authorization = `Bearer ${session?.accessToken}`;
}
return config;
},
(error) => {
return Promise.reject(error);
},
);
Following the docs, I wrapped my _app.js <Component> with
<Provider session={pageProps.session}>
<Component {...pageProps} />
</Provider>
Any ideas what I could try next?
Edit:
I call const [session, loading] = useSession(); on another part of the code (in the nextjs frontend) and there everything seems to be working
The problem is that if the axios call is made on the server side, then the interceptor will also be executed on the server side.
If that is the case, when calling getSession() on the server side, you also have to pass it the request or the context (see the note at the bottom of the manual entry for getSession)

Service workers "sync" operation is working while its offline?

I have a PWA project where I send the data to server. During this process, if the user is offline then the data is stored in indexedDb and a sync tag is registered. So, then when the user comes online that data can sent to the server.
But In my case the sync event gets executed immediately when the we register a sync event tag, which means the data is tried to be sent to server while its offline, which is not going to work.
I think the sync event supposed to fire while its online only, what could be issue here ?
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
This is how I register my sync tag
function onFailure() {
var form = document.querySelector("form");
//Register the sync on post form error
if ('serviceWorker' in navigator && 'SyncManager' in window) {
navigator.serviceWorker.ready
.then(function (sw) {
var post = {
datetime1: form.datetime1.value,
datetime: form.datetime.value,
name: form.name.value,
image: form.url.value,
message: form.comment.value
};
writeData('sync-comments', post)
.then(function () {
return sw.sync.register('sync-new-comment');
})
.then(function () {
console.log("[Sync tag registered]");
})
.catch(function (err) {
console.log(err);
});
});
}
}
And this is how the sync event is called
self.addEventListener('sync', function (event) {
console.log("[Service worker] Sync new comment", event);
if (event.tag === 'sync-new-comment') {
event.waitUntil(
readAllData('sync-comments')
.then(function (data) {
setTimeout(() => {
data.forEach(async (dt) => {
const url = "/api/post_data/post_new_comment";
const parameters = {
method: 'POST',
headers: {
'Content-Type': "application/json",
'Accept': 'application/json'
},
body: JSON.stringify({
datetime: dt.datetime,
name: dt.name,
url: dt.image,
comment: dt.message,
datetime1: dt.datetime1,
})
};
fetch(url, parameters)
.then((res) => {
return res.json();
})
.then(response => {
if (response && response.datetimeid) deleteItemFromData('sync-comments', response.datetimeid);
}).catch((error) => {
console.log('[error post message]', error.message);
})
})
}, 5000);
})
);
}
});
you mention
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
So I'm not sure which case is the one failing.
You are right that the sync will be triggered when the browser thinks the user is online, if the browser detects that the user is online at the time of the sync registration it will trigger the sync:
In true extensible web style, this is a low level feature that gives you the freedom to do what you need. You ask for an event to be fired when the user has connectivity, which is immediate if the user already has connectivity. Then, you listen for that event and do whatever you need to do.
Also, from the workbox documentation
Browsers that support the BackgroundSync API will automatically replay failed requests on your behalf at an interval managed by the browser, likely using exponential backoff between replay attempts.

Cannot read property 'Authorization' of undefined with Nuxt Auth & Axios

I have been using nuxt/auth-next and axios modules with nuxt project since last 3-4 months, everything was working fine since yesterday but now whenever I try to send axios request to public APIs without passing Authorization in headers, I get this error
Cannot read property 'Authorization' of undefined with Nuxt Auth & Axios
Attached is a screenshot of the page
below is my code in index.js store file
export const actions = {
async nuxtServerInit({ commit }, context) {
// Public profile
if (context.route.params && context.route.params.subdomain) {
context.$axios.onRequest((config) => {
config.progress = false
})
let { data } = await context.$axios.get(
`users/get_user_data_using_subdomain/${context.route.params.subdomain}`,
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
)
await context.store.dispatch('artists/setPublicProfile', data.user_data)
}
},
}
This happend to me to when I was using context.app.$axios instead of context.$axios within a injection
Nuxt server is looking for config.headers.common.Authorization.
The example below is a quick win for you:
let { data } = await context.$axios.get(
`users/get_user_data_using_subdomain/${context.route.params.subdomain}`,
{
headers: {
common: null, // or something like this: context.$axios.defaults.headers?.common
'Content-Type': 'multipart/form-data',
},
}
)

Cancelling promise in nuxt-axios response interceptor

Basically, my question is the exact one here https://github.com/axios/axios/issues/583. It can be done via throw new axios.Cancel('Operation canceled by the user.');.. But how can I do this in nuxt axios module?? I can not see it in the document and I tried $axios.Cancel('Error') but returned $axios.Cancel is not a constructor
Basically, the something like the snippet below is what I am looking for:
axios.interceptors.response.use(function (response) {
throw new axios.Cancel('Operation canceled by the user.');
}, function (error) {
return Promise.reject(error);
});
Emphasis on throw new axios.Cancel
While #nuxtjs/axios does not expose axios.Cancel, you could still import axios directly to get that symbol. Note axios is already a dependency of #nuxtjs/axios, so no extra dependency necessary.
Example (tested with #nuxtjs/axios v5.11.0):
// plugins/axios.js
import { Cancel } from 'axios'
export default function ({ $axios }) {
$axios.onResponse((response) => {
if (response.code !== 200){
throw new Cancel(response.msg)
}
})
}
With nuxt/axios v5.8.0 IsCancel available
v5.8.0 add CancelToken and isCancel to axios instance
Seems like nuxt-axios does not have any exact equivalent but I found a work around.
plugins/axios.js
export default function({ $axios, req, store, redirect, app }, inject) {
// const source = $axios.CancelToken.source()
const timeout = process.env.API_TIMEOUT || 10000
const errorHandling = function(error) {
console.log(`API ${error}`)
return new Promise(() => {})
}
$axios.onResponse((response) => {
// Any condition that could be considered an response based on standard response
if(response.code !== 200){
throw response.msg
}
})

Service in vue2JS - error in created hook

I'm new to vue2JS and currently I am trying to create my very first service in vue2 ever.
I've created basic file api.js with this code:
import axios from 'axios';
export default () => {
return axios.create({
baseURL: 'http://localhost:8080/',
timeout: 10000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
}
Code above is basic axios configuration which will be used in every service across entire app.
I import this file into my service:
import api from '../api.js';
export default {
getLatest () {
return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`, {
headers: {
'Content-Type': 'application/json'
}
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
}
Code above is responsible for making http request to backend rest API which give JSON in response.
And then finally I want to use this service inside my component <script></script> tags:
<script>
import { getLatest } from '../../../services/articles/getLatest';
export default {
data () {
return {
articles: []
}
},
created () {
const getLatestService = new getLatest();
console.log(getLatestService);
}
}
</script>
Here I want to execute code from service and actually execute this http request then save response in getLatestService constant and then console.log it and I should be able to see JSON in my browser console.
This doesn't work and give me this error in chrome console:
[Vue warn]: Error in created hook: "TypeError: WEBPACK_IMPORTED_MODULE_0__services_articles_getLatest.a is not a constructor"
And this error in command line:
39:35-44 "export 'getLatest' was not found in '../../../services/articles/getLatest'
Please help me to solve this problem. Additionally I want to refactor my code from service (second one) to use async await but I just can't find good example which would show me way to accomplish that.
EDIT 22.11.17
I added error which show in command line and { } when importing in component. I still didn't solve the problem.
EDIT 24.11.17
Looking for an answer I add more explanation of code I've posted and screenshot of files structure if maybe it can help.
I have check your code and what i can see is, in your api.js you have used
baseURL: 'http://localhost:8080/',
and in your service file
return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`
In your service file you have not define your localhost port, i think it should be like
return api().get(http://localhost:8080/obiezaca/ob_serwer/api/article/getLatest.php
If above is not an your issue then you should try
const getLatestService = getLatest();
Because getLatest() is a function and not an object.
This might solve your error issue.