i have an app which recieves token in my broswer url
http://localhost:8081/reset/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MmU2YWJmMmMzMzI0Mjk1NGQyNmVjZjIiLCJpYXQiOjE2NTk1MDIwNTEsImV4cCI6MTY1OTUwMjk1MX0.GIlKy_GI7HlfuB1WgD9HPxOGRZUX2_uOtOclrDTW3Y8
how can i remove (.) from my url
this is how i go to my route
{ name: "reset", path: "/reset/:token", component: Reset },
this is my script tag on how i call the function
<script>
import axios from "axios";
export default {
data() {
return {
password: "",
confirm_password: ""
};
},
mounted() {
console.log("the id is :" + this.$route.params.token);
},
methods: {
async submit() {
let token = this.$route.params.token;
let encoded = encodeURI(token);
return axios({
method: "post",
data: {
password: this.password,
token: this.$route.params.token
},
url: "http://localhost:5000/api/auth/updatePassword",
headers: {
"Content-Type": "application/json"
}
})
.then(res => {
console.log(res);
this.$router.push({ name: "login" });
})
.catch(error => {
console.log(error);
});
},
clear() {
this.$refs.form.reset();
}
}
};
</script>
i can't get the reset page until i remove the (.) please how can i encode the token
The token that you have is a JWT token, which should contain the two dots. I don't think removing them is a good idea. However, it looks like Vue router interprets the dots like a separator or something, causing the router to fail in finding the route.
What you might do is use a query string instead of a route param. You add the token to the url like:
http://localhost:8081/reset?token=eyJhbGciOiJ...
You should change the route to:
{ name: "reset", path: "/reset", component: Reset },
Now you can get it from the router with:
this.$route.query.token
Related
i've an app whcih sends email to users to reset their passwords
this is the link i send to the user email to be able to do password reset
http://localhost:8081/reset/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MmU2YWJmMmMzMzI0Mjk1NGQyNmVjZjIiLCJpYXQiOjE2NTk0ODkzODEsImV4cCI6MTY1OTQ5MDI4MX0.6omB-TkXXcwrjv0MaJQxltyERIoJZmkm8sY74AAqgxo
but each time i try to access the link i get
Cannot GET /reset/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
this is my route
{ name: "reset", path: "/reset/:token", component: Reset },
this is my script tag
<script>
import axios from "axios";
export default {
data: () => ({
valid: true,
password: "",
}),
mounted() {
console.log("the id is :" + this.$route.params.token);
},
methods: {
async handleSubmit() {
const response = await axios
.post("http://localhost:5000/api/auth/reset-password", {
newPassword: this.password,
token: this.$route.params.token
})
.then(res => {
console.log(res);
})
.catch(error => {
console.log(error);
});
},
}
};
</script>
please how can i go about these
I currently have a frontend auth app somewhat made with NuxtJS, where it will take in username/password fields and then use this.$auth.login to login.
I'm confused, though, on how to pass this info to the backend so it can verify that the username/password combination is correct. Currently my code will direct to the next page no matter what I put in the fields (makes sense since I haven't configured anything yet). I understand I need to use Axios POST requests somehow and I made an attempt at that but I don't really know what to do next. I don't know how to grab the token that contains my user data and push it to my backend (adonisJS) so I can check it against the database.
My login.vue component
<template>
<div>
<v-form #submit.prevent="loginUser">
<div>
<v-label>Username</v-label>
<v-text-field color='red' v-model="login.username" />
</div>
<div>
<v-label>Password</v-label>
<v-text-field color='red' v-model="login.password" />
</div>
<div>
<v-btn type="submit" color='purple'>Submit</v-btn>
</div>
</v-form>
</div>
</template>
<script>
export default {
data() {
return {
login: {
username: '',
password: ''
}
}
},
methods: {
async loginUser() {
const response = await this.$axios.post("/auth/users", {
email: this.email,
password: this.password,
}).then(
await this.$auth.login({
data: {
email: this.email,
password: this.password
}
}).then(() => {
this.$router.push('/dashboard')
}).catch(err => {
console.log(err)
})
).catch(err => console.log(err));
}
}
}
</script>
My nuxt.js.config (relevant parts)
axios: {
baseURL: 'http://localhost:3000/api', // Used as fallback if no runtime config is provided
},
auth: {
strategies: {
local: {
token: {
property: 'access_token',
required: true,
type: 'Bearer'
},
user: {
property: false, // <--- Default "user"
autoFetch: true
},
endpoints: {
login: { url: '/auth/login', method: 'post' },
logout: { url: '/auth/logout', method: 'post' },
user: { url: '/user', method: 'get' }
}
}
}
},
router: {
middleware: ['auth']
},
Can anyone help me out with what I need to do with axios? (I checked my storage to see if there was a token there and it just says "false".) Thank you!
You don't need to use axios post, this is how you should log in
methods: {
async loginUser() {
try {
//this will attempt to log in, and if successful it'll go to the home page unless you change the default redirects
const fields = {email: this.email, password: this.password};
await this.$auth.loginWith("local", { data: fields });
console.log("login successful");
} catch (errors) {
//an error occurred, could be wrong password or any other type of error
console.error(errors);
}
}
}
local is the strategy name and means that it's your own auth server, if you were using google for example you'd put google there, check out loginwith and local
the auth library already knows that your login url is /auth/login since you stated that in the nuxt config.
if you want to control where it goes after the login, look into the redirect options in the nuxt.config from the docs and specifically in this case home.
auth: {
redirect: {
home: '/'
}
}
I'm using nuxt.js, after I send a login request with email and password to the backend I get a response which contains a message, token and user informations, how can I access user informations in the response and save it inside some state in store.js after a successful login?
I wanted to save user object in user state down in store/index.js using an action saveUserAction which might be dispatched after a successful login, i dont know if thats right or not, any advise would be very helpful
Response
{
"message":"success",
"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNzFkYjA1MWM2MTYxMmE4YzAyNWI2YjU3N2xMzJiNzJjMjI0MzRlY2IzNzYwNTg2N2NjOWQ5ZWEwY2MiMJM3uYEiZ8GSlPlQhIctVErO2KzwXOBxifWWoM7et_qT-mgvfsk3ljwiQF9iPQw-WeekBx8J8lcmxDLESa3tfE1Re1Xk2flkcBLmiI4JN2YHh08U1U",
"user":{
"id":1,
"role_id":4587,
"firstname":"Hans",
"lastname":"newman",
"email":"newman#gmail.com",
"email_verified_at":null,
"phone":"89498",
"skype":"gdgdfg",
"birthdate":"2021-05-02",
"address":"asdfaf",
"postalcode":14984,
"city":"jisf",
"country":"isfisf",
"status":"mfof",
"created_at":"2021-06-16T09:33:08.000000Z",
"updated_at":"2021-06-16T09:39:41.000000Z",
"image":"1623835988-carlsen.png",
"description":"sfdgg",
"geo_lat":5.5,
"geo_lng":8.1
}
}
login.vue
<script>
import { mapActions } from 'vuex'
export default {
data() {
return {
auth: false,
email: '',
password: '',
}
},
methods: {
async login() {
const succesfulLogin = await this.$auth.loginWith('local', {
data: {
email: this.email,
password: this.password,
},
})
if (succesfulLogin) {
await this.$auth.setUser({
email: this.email,
password: this.password,
})
this.$router.push('/profile')
}
},
},
}
</script>
store/index.js
export const state = () => ({
user:{}
})
export const mutations = {
saveUser(state, payload) {
state.user=payload;
}
}
export const actions = {
saveUserAction({commit}, UserObject){
commit('saveUser');
}
}
Go to your vue devtools, vuex tab and look for auth, it should already be available. This answer may help you during your debugging: https://stackoverflow.com/a/68081536/8816585
Since you do have your user object in the response, this kind of configuration should do it, as shown in the documentation. No need to make some other vuex actions.
auth: {
strategies: {
local: {
token: {
property: 'token',
global: true,
},
user: {
property: 'user', // the name of your object in your backend response payload
},
endpoints: {
[...]
}
}
}
}
I'm using Axios to send user input to DRF api and it returns an auth token. I'm saving the token in vuex store. In another component. I'm trying to request another api endpoint with Axios with the latest token in the request headers. The issue I'm having is that Axios will either send the request with no token at all or with the token of the previous user that was logged in. It does not get the current token from the vuex store. I used Axios interceptors hoping that would help but it did not.
Login.vue
<script>
export default {
name: 'Login',
data () {
return{
email: null,
password: null,
token: '',
}
},
props: {
},
methods: {
submitForm () {
this.$store.dispatch('loginUser',{
email: this.email,
password: this.password
}).then(() =>{
this.$router.push({ name: 'List' })
}) .catch(err =>{
console.log(err)
})
},
}
}
</script>
store/index.js
import axios from 'axios'
import { createStore } from 'vuex'
export default createStore({
state: {
token: localStorage.getItem('token'),
},
mutations: {
getToken(state, token) {
localStorage.setItem('token', token)
state.token = token
}
},
actions: {
loginUser({ commit }, data){
axios({
method: 'POST',
url: 'http://localhost:8000/auth/login/',
headers: {'Content-Type': 'application/json'},
data: {
'email': data.email,
'password': data.password,
}
}).then(response =>{
commit('getToken', response.data['key'])
})
}
},
modules: {
}
})
List.vue
<script>
import axios from 'axios'
import store from '/src/store'
export default {
name:'List',
data () {
return {
entry: []
}
},
created() {
axios.interceptors.request.use(function (config){
let token = store.state.token
config.headers['Authorization'] = 'Token ' + token;
return config;
})
axios({
method: 'GET',
url: 'http://localhost:8000/journal/',
headers: {'Content-Type': 'application/json'},
}).then(response =>{
this.entry = response.data
}) .catch(err =>{
console.log(err)
})
}
}
</script>
I thought the point of the interceptor was to get the token before actually making the get request, but it does not seem to be doing that.
Not exactly sure why this works but rewriting my loginUser action like this solves my issue.
actions: {
loginUser({ commit }, data){
return new Promise ((resolve, reject) => {
axios({
method: 'POST',
url: 'http://localhost:8000/auth/login/',
headers: {'Content-Type': 'application/json'},
data: {
'email': data.email,
'password': data.password,
}
}).then(response =>{
commit('getToken', response.data['key'])
resolve()
}).catch(err => {
reject(err)
})
})
}
},
I think it's because return new Promise basically interrupts the the initial promise in Login.vue making sure the client doesn't make an api request without the correct token from the server but I'm not sure.
I've been trying to get this to work for two days now. I'm a brand new user to Nuxt (although I've used Vue for a few years now), so I'm just trying to wrap my brain around how this all works.
In my Nuxt project I have the Axios module installed:
nuxt.config.js
export default {
plugins: [
...
'~/plugins/axios',
],
axios: {
baseURL: 'https://my-url.com/wp-json/wp-v2',
https: true,
},
}
plugins/axios.js
export default ({ $axios, env }) => {
$axios.onRequest(config => {
$axios.setToken(env.WP_API_KEY, 'Bearer');
});
}
And in my page, I'm trying to use the asyncData function to pull data from my WordPress API, as such:
export default {
async asyncData(context) {
const data = await context.$axios.$get('/media');
console.log(data);
return { data };
}
}
I keep receiving a 401 Not Authorized error however, essentially stating that my Authorization: Bearer <token> isn't being passed through. Using Postman however, I can verify that this endpoint does indeed work and returns all of the JSON I need, so the problem must lie in the way I have the axios global header set up.
It's been tough finding any real example on how to set a global header using the Nuxt/Axios module. I see in the docs how to use setToken, however it doesn't exactly show where to place that.
What do I have set up wrong, and how do I fix it?
Pretty typical that I get it working 15 minutes after I post a question.
Setting the header like this instead seems to work. I'm not sure why the setToken method didn't want to work.
export default ({ $axios, env }) => {
$axios.onRequest(config => {
config.headers.common['Authorization'] = `Bearer ${env.WP_API_KEY}`;
});
}
If you are using Nuxt auth module, Here is how I have achived.
// nuxt.config.js
modules: [
'#nuxtjs/auth',
'#nuxtjs/axios',
],
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/auth/login', method: 'post', propertyName: 'accessToken' },
logout: false,
user: { url: '/auth/me', method: 'get', propertyName: false }
},
}
},
redirect: {
login: '/auth/signin',
logout: '/auth/signin',
callback: false,
home: false,
},
cookie: false,
token: {
prefix: 'token',
},
plugins: ['~/plugins/auth.js'],
},
// plugins/axios.js
export default function ({ $axios, $auth, redirect, store }) {
$axios.onRequest((config) => {
config.headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': store.state.auth.tokenlocal, // refers to nuxt.config.js->auth.token
}
})
$axios.onError((error) => {
if (error.response.status === 500) {
redirect('/error')
}
})
}
// store/index.js
export const getters = {
authenticated(state) {
return state.loggedIn;
},
user(state) {
return state.user;
}
};
export const state = () => ({
busy: false,
loggedIn: false,
strategy: "local",
user: false,
});
If you need to customize axios by registering interceptors and changing global config, you have to create a nuxt plugin.
export default ({ $axios, env }) => {
$axios.onRequest(config => {
config.headers.common['Authorization'] = `Bearer ${env.WP_API_KEY}`;
});
}
Adding axios interceptors