VueJs2 Query Params Not Passing - vuejs2

I'm trying to code password-forget,reset system. In the password reset step, token is sending via url like that;
http://link-to-app/reset-password?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX
In vuejs side. I want to get this token params but I can not. I try that;
created() {
console.log(this.$route.params); // Empty Object {}
},
Also I try to redirect with query params with router.push, it is redirecting but not sending query params;
this.$router.push({ path: '/reset-password', params: { token : 1234 } })
|
http://link-to-app/reset-password

You should try this.$route.query.token instead of this.$route.params to get token from the url

Related

Nuxt pass props programmatically, through router

i'm using Nuxt
I'm having troubles with passing data from one page to another
I would like programmatically to navigate to other page, and pass some data to other page (in this case its javascript object)
So here is my code so far:
I have a component in which I navigate from:
this.$router.push({ path: 'page/add', props: { basket: 'pie' } });
And here is a component where I would like to get data, its a Nuxt page:
export default {
components: { MyComponent },
props: [
'basket' // this is also empty
],
async asyncData(data) {
console.log(data); // data does not contain basket prop
},
meta: {
breadcrumb: {
path: '/page/add',
},
},
};
</script>
But when I try to acces props, or data or data.router it does not contain basket prop ??
Also, I would not like to use query, or params because they change URL
[1]: https://nuxtjs.org/
You can use localstorage and save you'r data in it:
localStorage.setItem("nameOfItem", Value);
and delete it if you want after you'r done with it:
localStorage.removeItem("nameOfItem");
If you don't want to use query or params, I would check out the vuex store. Its a really cool way of storing global variables and use it in multiple pages.
Vuex store
Navigate to a different location
To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.
The argument can be a string path, or a location descriptor object. Examples:
// literal string path
this.$router.push('/users/eduardo')
// object with path
this.$router.push({ path: '/users/eduardo' })
// named route with params to let the router build the url
this.$router.push({ name: 'user', params: { username: 'eduardo' } })
// with query, resulting in /register?plan=private
this.$router.push({ path: '/register', query: { plan: 'private' } })
// with hash, resulting in /about#team
this.$router.push({ path: '/about', hash: '#team' })
reference:
https://router.vuejs.org/guide/essentials/navigation.html#navigate-to-a-different-location
To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.
What you are trying to accomplish is not conform with the browser (history etc.) or
http protocol (GET/POST).
Also, when using path params and other variables, such will be ignored, as per the documentation.
Note: params are ignored if a path is provided, which is not the case for query, as shown in the example above. Instead, you need to provide the name of the route or manually specify the whole path with any parameter.
Using props here is very likely the wrong approach, as you will never get that data to the component.

Why the url become like this(add ? before #) after redirecting and how can I redirect correctly

I'm making a login page with redirect function,and the logic following like this:
if I never logged and I enter the url '/home/qiputranscode',it will redirect to
'http://127.0.0.1:8000/#/login?redirect=%2Fhome%2Fqiputranscode'.
then I need to request the server with username and pwd to get token for entry '/home/qiputranscode' page.
but after inputting my username and pwd the url become this:
'http://127.0.0.1:8000/?#/login?redirect=%2Fhome%2Fqiputranscode'
and didn't request the server or redirect to '/home/qiputranscode'.
so, why the url add ? in itself before #.
and what's difference between them, I will be grateful if u gave me any suggestion
the redirect code like this:
router.beforeEach((to, from, next) => {
if (to.matched.some(r => r.meta.requiredAuth)) {
if (store.state.token) {
next()
} else {
next ({
path: '/login',
query: {redirect: to.fullPath}
})
}
} else {
next()
}
});
The part after ? is the query with key=redirect and value=full path
To redirect to the saved path call this after login
this.$router.push({ path: this.$route.query.redirectTo })
And you also need to prevent the default form behavior
<form v-on:submit.prevent ...

how to redirect from one url to another in vue

I m trying to redirect from one URL to another URL using Vue router eg code
{
path: '/verifyemail/:id/:token',
//can i somelogic here when user entered
},
{
path: '/login',
component:login
},
what I m trying to do? when the user registered himself. server send email verification link to his email when a user clicks on verify button from his email then it should first call verifyemail url. where it has an ajax call with a parameter which i m getting from verifyemail url now after the success it should move to login url note:- i don't have any component in my verfiyemail route
is it possible to do this or is there anyother way to achieve this
The route configuration is only data, so there's not really any way to do this exactly as you'd like.
If you create a component to handle the /verifyemail/ route you can just use this.$router.push(redirectToMe) in it. See the Vue Router docs for more information.
Alternatively, this sounds more like something a backend server would handle on it's own, so maybe you don't even need Vue to worry about it.
finally, I arrive with one solution may be this help other
let start, I send the email with verify button which has link something like "localhost:8080/#/verfiyemail/("ACCESSTOKEN")" NOW I my vue part i does something like
in vue-route
path: '/verifyemail/:uid',
beforeEnter:(to, from, next) => {
let uid=to.params.uid;
next({ path: '/', query: { id: uid}})
}
},
{
path: '/',
name: 'Login',
component: Login,
},
and i my login.vue
created(){
this.verfiyemai();
},
methods:{
verfiyemai(){
var _this=this
var submit=0
if(this.$route.query.id!=undefined ){
if(this.$route.query.id.length<=50){
this.$router.push('/');
submit=1;
}
if(submit==0){
this.$http.get('/api/users/confirm?uid='+this.$route.query.id+'')
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
});
}
}
},
}
from email, I redirect the user to verfiyemail with token id as a parameter from verifyemail route, after that I redirect to the login URL passing the parameter as query and in my login vue I had created a method which checks query length if it greater than 50 then it will post axios response to the server

Checking auth token valid before route enter in Vue router

I have a simple use case, where my application is using vue-router and vuex. Then store contains a user object which is null in the beginning. After the user is validated from the server it sends back an user object which contains a JWT auth token which is assigned to the user object in the store. Now lets assume that the user came back after 3 hours and tried to visit a route or perform any other action, considering that the auth token has expired by then, what would be the best way to check that(need to call axios post to check it) and redirect user to the login page. My app will have loads of components so I know I can write logic to check the token valid in the mounted hook of each component but that would mean repeating it all of the components. Also I don't want to use the beforeEach navigation guard because I cannot show any visual feedback to the user like checking... or loading....
I do something similar in one of my projects, it's actually deceptively difficult to handle these types of situations, but you can add a beforeEnter guard to your protected routes, then redirect if the authentication failed.
const guard = function(to, from, next) {
// check for valid auth token
axios.get('/api/checkAuthToken').then(response => {
// Token is valid, so continue
next();
}).catch(error => {
// There was an error so redirect
window.location.href = "/login";
})
};
Then on your route you can do:
{
path: '/dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
guard(to, from, next);
}
},
You may notice I've used location.href rather than router.push. I do that because my login form is csrf protected, so I need a new csrf_token.
Your other issue is going to be if the user tries to interact with your page without changing the route (i.e. they click a button and get a 401 response). For this I find it easiest to check authentication on each axios request and redirect to login when I receive a 401 response.
In terms of adding a loading spinner during the guard check you can simply add a loading flag to your vuex store then import your store into your router. Honestly though I wouldn't bother, on a decent production server the check will be done so quickly that the user is unlikely to ever see it.
Try Vue.JS Mixins
You can define a Global Mixin and use it via Vue.use(myMixin) - then all Components will inherit this mixin. If you define a mounted or probably better activated hook on the mixin, it will be called on every component.
There you can use everything a component can do - this will point to your component. And if the component also defines a hook itself, the mixin hook of the same type will run before the components own hook.
Or try a single top-level login component
We used a little different solution - we have a single component which handles everything login-related, which exists outside of the router-view in the parent index.html. This component is always active and can hide the div router-view and overlay a loading message or a login-screen. For an intranet-application this component will also use polling to keep the session alive as long as the browser stays open.
You can load of your router-navigation to this component. - So a child-component which wants to trigger a router-navigation just sets a global reactive property navigateTo which is watched by the top level authentication component. This will trigger an authentication check, possibly a login-workflow and after that the top-level component will call $router.push() With this approach you have complete control over any navigation.
You can use interceptors to silently get the auth token when some request happens.
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const rToken = window.localStorage.getItem('rToken');
return axios.post('url/to/get/refresh/token', { rToken })
.then(({data}) => {
window.localStorage.setItem('token', data.token);
window.localStorage.setItem('rToken', data.refreshToken);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.token;
originalRequest.headers['Authorization'] = 'Bearer ' + data.token;
return axios(originalRequest);
});
}
return Promise.reject(error);
});
Because you use vuex, you can add some state like isLoading or isChecking.
And in your router.beforeEach, you can check and set isLoading or isChecking follow your current checking state. Then you can show loading message follow this state.
In our route.js we check in beforeEnter hooks the user has token or
not.
route.js
{
path: '/dashboard',
name: dashboard,
meta: {
layout: 'home-layout'
},
components: {
default: Dashboard,
header: UserHeader
},
beforeEnter: ifAuthenticated,
}
route.js
const ifAuthenticated = (to, from, next) => {
if (localStorage.getItem(token)) {
next();
return;
}
router.push({
name: 'login',
params: {
returnTo: to.path,
query: to.query,
},
});
};

Axios params not appending correctly to URL

I'm trying to use params for a post request using Axios. However, when I check the XHR in Chrome, the params don't seem to be appended to the URL.
If I do this, it works:
axios.post('/!/Like/like?id=' + this.id + '&_token=' + this.csrf_token)
But if I try this, I get an error:
axios.post('/!/Like/like', {
params: {
id: this.id,
_token: this.csrf_token
}
})
In other words, the url needs to be:
/!/Like/like?id=1234&_token=zYXW-123
Any ideas what I might be doing wrong?
The second parameter in axios.post is the data. If you wanted to post the way you are doing here, you would need to pass your params as the third argument.
axios.post('/!/Like/like', "", {
params: {
id: this.id,
_token: this.csrf_token
}
})