Laravel: Can't find access_token and refresh_token on request - javascript

When I'm logging in, it seems my data response different I'm confused cause I'm looking for access_token and refresh_token but the only available here X-CSRF-TOKEN and X-XSRF-TOKEN then there's no more other token
BTW, I'm using vue js and I want to store my access_token to localStorage. And also I'm using default laravel authentication for the login
export default{
$validates: true,
data(){
return{
login:{
username : '',
password : '',
remember : ''
},
disabled: 0,
indeterminate : false,
showLoader: false
}
},
methods:{
submit(){
this.showLoader = true;
this.$validator.validateAll().then((result) => {
if(result){
console.log(this.login.username);
/*axios.post('/prod/login', this.login)
.then(response => console.log(response));*/
axios({
method:'post',
url : '/prod/login',
data: {
email : this.login.username,
password : this.login.password,
remember : this.login.remember
},
responseType: 'JSON'
})
.then(response=>{
if(response.status == 200){
console.log(response);
}
})
.catch(error => {
if (error.response) {
console.log(error.response);
}
});
console.log('submited');
return;
}
console.log('mali e');
});
}
},
mounted(){
}
}

Related

Nuxt auth user reset after browser refresh

i'm building an app with user login and register info. I use nuxt/auth module for handling the authentification. Whenever the user get logs in the state changes to true without a problem. The only issue i'm having is when i call set user method , the user info get registered successfully, but whenever i refresh the browser i lose the user data even though in the first place it was set successfully.
my nuxt.js config for nuxt auth module
auth: {
strategies: {
local: {
token: {
property: "token",
global: true,
},
redirect: {
"login": "/account/login",
"logout": "/",
"home": "/page/ajouter-produit",
"callback": false
},
endpoints: {
login: { url: "http://localhost:5000/login", method: "post" },
logout: false, // we don't have an endpoint for our logout in our API and we just remove the token from localstorage
user:false
}
}
}
},
My register/login component
async typeForm(e) {
this.typesubmit = true;
// stop here if form is invalid
this.$v.$touch();
if (this.$v.typeform.$anyError) {
return;
}
const user = await axios.post(`${baseUrl}register`,{
username:this.typeform.username,
password:this.typeform.password,
email:this.typeform.email,
tel:this.typeform.tel,
adresse:this.typeform.adresse,
store:this.typeform.store,
})
.then(response => {
console.log(response.data)
return response.data.user;
}).catch( (error) => {
this.error = ''
this.error = error.response.data
})
if(user){
let loginData = {email:this.typeform.email, password:this.typeform.password}
const response = await this.$auth.loginWith('local', { data: loginData})
.then(response => {
this.$auth.setUser(response.data.user) // the user is set without a problem, everything works fine.
return response.data;
}).catch( (error) => {
this.errors = error.response.data
console.log(error.response)
})
}
}
When i console log the state and the user in the first place everything works fine
console.log(this.$store.state.auth.user) // logs all user data i get from the api call. but when i refresh i get an empty object
console.log(this.$store.state.auth.loggedIn) // logs true , and even after i refresh it's still true
please help
Problem solved. what i did is to add to my login function
this.$auth.$storage.setUniversal('user', response.data.user, true)
works like a charm.
I have the samie issue.
After added this.$auth.$storage.setUniversal('user', response.data.user, true), the user is logged out after refreshing the page.
Here is my code :
this.$auth
.loginWith("local", {
data: {
email: this.connexionLogin,
password: this.connexionPassword
}
})
.then( (response) => {
this.$auth.setUser(response.data.user);
this.$auth.$storage.setUniversal('user', response.data.user, true)
this.$emit("connexionOk");
and my nuxt.config :
auth: {
watchLoggedIn: true,
resetOnError: true,
redirect: {
login: "/admin/login",
logout: "/admin/login",
callback: "/callback",
home: '/admin/', // Pour ne pas être redirigé vers la home suite authentification
},
strategies: {
local: {
token: {
property: "tokens.access.token",
},
user: {
property: 'user',
autoFetch: false
},
endpoints: {
login: {
url: "v1/auth/login",
method: "post",
},
logout: false,
},
},
},
},

Unable to access response.status with React from a custom rails API

I am trying to get the status of a request I do from a React website I am working on, using axios to fetch make requests to a RoR API I developed. I would like to confirm that the POST request succeeded by accessing the status value from this (which is the output of a console.log(response):
Promise { <state>: "pending" }​
<state>: "fulfilled"​
<value>: Object { data: {…}, status: 201, statusText: "Created", … }​​
config: Object { url: "pathname", method: "post", data: "{\"user\":{\"email\":\"lou10#email.com\",\"username\":\"lou10\",\"password\":\"azerty\"}}", … }​​
data: Object { data: {…} }​​
headers: Object { "cache-control": "max-age=0, private, must-revalidate", "content-type": "application/json; charset=utf-8" }​​
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 201
statusText: "Created"​​
<prototype>: Object { … }
index.jsx:51:11
But when I try a console.log(response.status) all I get is an undefined.
Here is the code :
import axios from 'axios';
import { BASE_URL } from "./config.js";
const post = async (
endpoint,
body = null,
jwt_token = null,
header = { "Content-Type": "application/json" }) => {
let opt = header;
if (jwt_token){
opt["Authorization"] = jwt_token
}
try {
const response = await axios.post(BASE_URL + endpoint, body, { headers: opt })
return response
} catch (err) {
console.error(`An error occurred while trying to fetch ${endpoint}. ${err}`);
}
}
export default post;
const handleSignup = async ({ email, username, pwd }) => {
let body = {
user: {
email: email,
username: username,
password: pwd
}
};
return await post("/users", body);
};
useEffect(() => {
if (passwordCheck === false) {
console.log("Passwords do not match");
} else if (passwordCheck === true && userData) {
const response = await handleSignup(userData);
console.log(response.status);
// history.push({ pathname: "/", state: response.status });
}
}, [passwordCheck, userData]);
I am thinking to change the response from my API, but I really doubt it is the right approach.
Edit 1: adding some complementary code
you have to declare the function you give in parameter to useEffect as async to be able to use await inside for your async function handleSignup
useEffect(async () => {
if (passwordCheck === false) {
console.log("Passwords do not match");
} else if (passwordCheck === true && userData) {
const response = await handleSignup(userData);
console.log(response.status);
// history.push({ pathname: "/", state: response.status });
}
}, [passwordCheck, userData]);

Issue with fetch: Getting type error failed to fetch

I'm trying to make a post call to the backend server, but I keep running into this error:
TypeError: Failed to fetch
I've looked over the code a bunch of times but can't seem to find the issue. Here is the code:
async doLogin() {
if(!this.state.email || !this.state.password) {
return
}
this.setState({
buttonDisabled : true
})
try {
let res = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
console.log(res)
let result = await res.json()
console.log(result)
if(result && result.success) {
UserStores.isLoggedIn = true
UserStores.email = result.email
alert(result.msg)
} else if(result && result.success === false) {
this.resetForm()
alert(result.msg)
}
} catch(e) {
console.log('doLogin error: ', e)
this.resetForm()
}
}
This is an example response payload:
{
"success": true,
"email": "mfultz956#gmail.com",
"msg": "Login Verified!"
}
Login Call - Network Tab
Login Call - Headers
change it to :
let res = await fetch('http://localhost:your_api_server_port/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})

Axios POST method: Network Error - React Native

When i send request with my Google Cloud address from postman its ok but from android studio/react-native/axios its give an error.
[Error: Network Error]
This is my code:
constructor(props){
super(props);
this.state = {
email: '',
password: '',
error: '',
loading: false
};
}
handleLoginUser(){
const { email, password } = this.state;
this.setState({ error: '', loading: true });
axios.post("https://serverip/users/login",
{
'email': 'email',
'password': 'password'
},
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
},
}
)
.then(response => {
console.log(response);
return response.json();})
.then(data => {
if (result.success){
alert("Login successful");
}
else
alert("Unable to Login");
})
.catch((error) => {
console.log(error);
});
}
Thanks for your helps.

Can't Get Error Message From Axios Response in React Native

I am writing a mobile application with using React Native. At some part, I need to send a post request and get response including the error part. So, for some certain input, API(my own) returns 409 with a message. Example return:
{
"status": 409,
"message": "E-mail is already exists!"
}
Here, I want to take that message and show to the user. This is what I tried:
UserService.signup({ fullName, email, username, password })
.then(response => {
this.setState({ signUp: true });
if (response.result) {
Toast.show(messages.successfulSignUp, {
backgroundColor: "green",
duration: Toast.durations.LONG,
position: Toast.positions.TOP
});
this.props.navigation.navigate("SignIn");
} else {
}
})
.catch(error => {
Toast.show(error.message, {
backgroundColor: "red",
duration: Toast.durations.LONG,
position: Toast.positions.TOP
});
this.setState({ signUp: false });
});
I tried error.message, error.response, error, error.data keys, but it always says TypeError: undefined is not an object (evaluating 'error.message'). So, how can I get the message from error object?
Edit: This is how I send the request:
import { post } from "./api";
export default {
signup: ({ fullName, email, username, password }) => {
return post("/user/register", { fullName, email, username, password });
}
};
export const request = config => {
return new Promise((resolve, reject) => {
axiosInstance
.request({
url: config.url,
method: config.method || "get",
data: config.body,
headers: {
"Content-Type": "application/json",
"X-Auth-Token": store.getState().auth.token
}
})
.then(response => {
resolve(response.data);
})
.catch(error => {
reject(error.data);
});
});
};
export const post = (url, body = {}) => {
return request({
url,
body,
method: "post"
});
};
Finally I solved this issue. I had to change my request method and the way I reach out to the error:
export const request = (config) => {
return new Promise((resolve, reject) => {
axiosInstance.request({
url: config.url,
method: config.method || 'get',
data: config.body,
headers: {
'Content-Type': 'application/json',
'X-Auth-Token': store.getState().auth.token,
}
}).then(response => {
resolve(response.data)
}).catch(error => {
reject(error.response)
})
})
}
// This is how reach out to the error message:
console.log(error.data.message);
Depending on what the backend returns, the error message in axios is in response.data of the error object.
.catch(error => {
const errResponse = (error && error.response && error.response.data)
|| (error && error.message);
reject(errResponse);
});

Categories

Resources