How to repeat action with query, in case of authentication issues? - vue.js

I have get menu action with authentication.
async getMenu({rootState, commit}) {
try {
const { auth, lang } = rootState;
const {items} = await this.$axios.$get(`/api/${ lang.locale }/menu`, {
headers: {
'Authorization': `bearer ${auth.token}`,
'Accept-Language': `${lang.locale}`
},
});
if (items) {
// set items
commit('setMenu', items);
}
} catch (error) {
console.log({Error: error})
}
}
In case of error, I submit request with refresh token
$axios.onError(async (error) => {
const code = parseInt(error.response && error.response.status);
const message = error.response && error.response.data && error.response.data.error;
if (code === 403) {
await store.dispatch(
'auth/refreshToken',
{ refreshToken: store.state.auth.refreshToken },
{ root: true }
);
How to repeat action after get token ?

Use
$axios.defaults.validateStatus = (status) => {
return [200, 402].indexOf(status) !== -1;
};
$axios.onResponse(async (response) => {...}

Related

react native make accessToken global

im using rn-secure-storage to save authState when using oauth2, then i have class AppHelper to control all network function like below:
import RNSecureStorage, { ACCESSIBLE } from 'rn-secure-storage'
export const accessToken = async() => {
await RNSecureStorage.get("authState").then((value) => {
console.log("authState", value);
return JSON.parse(value).accessToken
}).catch((err) => {
console.log("can not get authState", err);
});
};
export const getData = (url, tag = 'getData') => {
return fetch(url, {
method : 'GET',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization' : 'Bearer ' + accessToken
}
})
.then((response) => {
console.log(tag, 'Bearer ' + accessToken);
return response.text();
})
.then((json) => {
console.log(tag, json)
return json;
})
.catch((error) => {
handleError(err)
console.log(tag, error, url)
});
}
export const handleError = (error) => {
if (error.response.code == 401){
alert('Unauthorized')
}else{
console.log('network call failed', error)
}
}
im coding native before, so im not familiar with React native syntax. I just want to get access token to apply in network call, but my code show error:
_getMasterInfoApi Bearer function _callee() {
return _regenerator.default.async(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return _regenerator.default.awrap(_rnSecureStorage.default.get("authState").then(function (value) {
console.log("authState", value);
return JSON.parse(value).accessToken;
}).catch(function (err) {
handleError(err);
}));
case 2:
case "end":
return _context.stop();
}
}
}, null, null, null, Promise);
}
Can anyone help? thanks in advance

no response after axios.post()

Hey I'm working on a Login system on my vue project and have the problem that there seems to be no response from the backend.
This is the backend function:
auth.post('/login', async function (req, res) {
const { email, password } = req.body;
console.log(req);
if(email !== "" && password !== "") {
const account = await User.findOne({ where: { email: email} });
if (account) {
if (await account.validPassword(password)) {
// Generate an access token
const accessToken = jwt.sign({ id: account.id }, SECRET);
const account_data =
{
'id': account.id,
'firstName': account.firstName,
'lastName': account.lastName,
'email': account.email,
'isAdmin': account.isAdmin
}
res.send({accessToken, account_data});
} else {
res.status(200).json("Username or password incorrect");
}
} else {
res.send('Username or password incorrect');
}
} else {
res.send('Username or password incorrect');
}
})
This is the method were I call the action
methods: {
async loginUser(){
let user = await this.$store.dispatch('loginUser', this.loginInfo);
if(user.error){
alert(user.error)
} else {
alert('Thank you for signing in, ' + user.firstName);
}
},
}
This is the action:
async loginUser({commit}, loginInfo){
console.log(loginInfo)
try{
let response = await axios({
method: 'POST',
url: 'http://localhost:4000/api/auth/login',
data: loginInfo,
headers: {
// Overwrite Axios's automatically set Content-Type
'Content-Type': 'application/json'
}});
let user = response.data;
console.log(user);
commit('SET_CURRENT_USER', user);
} catch (e){
alert(e);
return {e}
}
}
Neither the console.log in the try function or in the catch function is triggered.

async / await is not waiting for the response

I am requesting an api using POST method. but after calling the RemoteRequest function using await. It's not waiting for the response return. It directly executes the remaining code in the register.js by this im getting the status = undefind in the console.log.
register.js
const DeviceUniqueId = DeviceInfo.getUniqueId();
const requestBody = { phone: phone, username: username };
const status = await RemoteRequest(URLs.APP_REGISTER,
'POST', DeviceUniqueId, requestBody);
console.log('status====>', status);
this.setState({
loading : false
});
remotereuqest.js
export const RemoteRequest = async (url, method, DeviceUniqueId, requestbody) => {
console.log(url, method, DeviceUniqueId, requestbody);
NetInfo.fetch().then((state) => {
if (state.isConnected) {
fetch(url, {
method : method,
headers : {
Accept : 'application/json',
'Content-Type' : 'application/json',
DEVICEID : DeviceUniqueId,
'Accept-Charset' : 'utf-8'
},
body : JSON.stringify(requestbody)
})
.then((response) => {
console.log('reponse=====>', response);
return response.json();
})
.then((responseData) => {
console.log(responseData);
if (responseData.status == 'OK' && responseData.code == 200) {
return responseData.code;
}
return null;
})
.catch((error) => {
console.log(error);
if (error.message == 'Network request failed') {
showMessage({
floating : true,
message : 'Connection error',
description : 'you have no Internet Connection',
type : 'alert',
backgroundColor : 'red'
});
return null; //503
}
else {
showMessage({
floating : true,
message : 'Internal Server Error',
description : 'please try again after some time',
type : 'alert',
backgroundColor : 'red'
});
throw error;
return null;
}
})
.done();
}
else {
showMessage({
floating : true,
message : 'Connection error',
description : 'you have no Internet Connection',
type : 'alert',
backgroundColor : 'red'
});
return null; //503
}
});
};
You need to await for all promises within the function, otherwise they still get executed asynchronously. Something like this:
await NetInfo.fetch().then( async (state) => {
if (state.isConnected) {
await fetch(url, {
...
}
}
});
When you use .then() the code after it gets executed immediately, so instead you should await the responses and then do the work without .then()-s.
const state = await NetInfo.fetch();
if (state.isConnected) {
const response = fetch(url, ...);
console.log(response);
...
}

React Native - FETCH Response is empty - API Status 500 - POST Call

signIn = () => {
//post data to express backend
fetch('http://10.0.2.2:3000/api/v1/auth', {
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: `login=${this.state.login}&password=${this.state.password}`
})
.then((response) => response.json())
.then ((res => {
if(res.status === 200) {
AsyncStorage.setItem('user', this.state.login);
this.props.navigation.navigate('Authorized')
} else {
alert("Response:", res);
}
}))
.done();
}
The above is for React-Native. And below is the express backend:
router.post('/', function(req,res){
var login= req.body.login;
var password = req.body.password;
var sql = `SELECT * FROM users WHERE username = '${login}' OR number = '${login}' AND password = ${password}`
db.query(sql, function (err, rows, fields) {
if (err) {
res.status(500).send({error: 'Something went wrong!'})
} else {
if(rows.length > 0) {
if (rows[0].password == password) {
res.status(200).send({success: 'Login Successful'})
}
} else {
res.status(404).send({error: 'Email or Password does not match!'})
}
}
})
});
I think there is nothing getting into a response or maybe some other problem which I am unable to figure out the moment.

IONIC 4 - Loading Controller In Http interceptor......Not able to create and dismiss properly due to Asynchronous call

I want to create loader for each http call and dismiss it when reponse is there....tried some code.....which shows sometimes mulitple loaders on each other...snap is there of code..
interceptor.ts
intercept(request: HttpRequest < any >, next: HttpHandler): Observable < HttpEvent < any >> {
request = request.clone({
headers: request.headers.set('Accept', 'application/json')
});
this.commonServices.showLoader();
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.commonServices.hideLoader();
}
return event;
}),
catchError((error: HttpErrorResponse) => {
this.commonServices.hideLoader();
if (error.status === 401) {
this.storage.clear();
this.router.navigate(['login']);
if (error.error.success === false) {
this.commonServices.forToast("Login failed");
} else {
//this.router.navigate(['login']);
}
}
return throwError(error);
}));
}
CommonService.service.ts
async showLoader() {
if (!this.loader) {
this.loader = await this.loadingController.create({ message: 'Loading' });
}
await this.loader.present();
}
async hideLoader() {
if (this.loader) {
await this.loader.dismiss();
this.loader = null;
}
}