How to import localstorage data on axios create - javascript

I have a component inside React for handling URL calls, it simply has a baseurl and headers I use everywhere in my application.
The problem is when there is no data in localStorage I get an error and the whole application stops.
If I use if condition I can't export inside it because export has to be at the top level.
import axios from "axios";
export default axios.create({
baseURL: `http://www.homrz.com/re_homrz/api/admin/`,
// headers: {
// Authorization: `Bearer ${JSON.parse(localStorage.getItem("user")).token}`,
// "Content-Type": "application/json",
// },
});

I think this may help
import axios from "axios";
let token = JSON.parse(localStorage.getItem("user")).token
export default axios.create({
baseURL: `http://www.homrz.com/re_homrz/api/admin/`,
headers: {
Authorization: token ? `Bearer ${token}` ? null,
"Content-Type": "application/json",
},
});

Make one file auth-header.js with below code
export function authHeader() {
let user = JSON.parse(localStorage.getItem('user'));
if (user !== null && user !== "" && user !== undefined) {
return {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + user.token
};
} else {
return {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
}
}
Then use it like below,
import axios from "axios";
import { authHeader } from './auth-header';
export default axios.create({
baseURL: 'http://www.homrz.com/re_homrz/api/admin/',
headers: authHeader(),
});

Related

Automatic reload import React

Currently,
I've made an axios common to calling API as:
export const API_LOCAL = axios.create({
baseURL: process.env.REACT_APP_BASEURL,
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
timeout: 30000,
});
First time when I start to import and use file with this export as API_LOCAL, I'm not use the 'Authorization', the localStorage.getItem('token') is null. Then I'll get some data and set back to localStorage.setItem('token','SOME_SAMPLE_TEXT').
After that, when in another calling which use API_LOCAL, I think it's cached because the API_LOCAL with localStorage.getItem('token') is always null.
Could I set up for the dynamic reload import file to get latest data?
Thank you for any guides.
the best way to handle Bearer token is via interceptor.
You can do something like
axios.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if ( token != null ) {
config.headers.Authorization = `Bearer ${token}`;
}
}
This way every axios request will be sent with your auth token

How to wrap into async the Cookies.get of my axios object

I have this axios object, and I have noticed that sometimes it fails to get accesstoken because of async issues.
How would you go about awaiting Cookies.get('accesstoken')
This is my code
import axios from 'axios';
import constants from '../constants.js';
import Cookies from 'js-cookie';
const API = axios.create({
baseURL: `${constants.urlBackend}`,
timeout: 10000,
// headers: {
// 'Content-Type': 'application/json'
// },
});
API.interceptors.request.use(
config => {
var accesstoken = Cookies.get('accesstoken');
if (accesstoken) {
config.headers.Authorization = `Bearer ${accesstoken}`;
} else {
delete API.defaults.headers.common.Authorization;
}
return config;
},
error => Promise.reject(error)
);
export default API;
I dont think I can wrap the API.interceptos.request.use in an async function, or at least it didnt seem to work

How to adapt this axios object with bearer tokens that allows GET, to use POST methods?

I have managed to make this run: How to modify axios instance after exported it in ReactJS?
And it looks like this:
import axios from 'axios';
import constants from '../constants.js';
import Cookies from 'js-cookie';
const API = axios.create({
baseURL: `${constants.urlBackend}`,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
API.interceptors.request.use(
config => {
var accesstoken = Cookies.get('accesstoken');
if (accesstoken) {
config.headers.Authorization = `Bearer ${accesstoken}`;
} else {
delete API.defaults.headers.common.Authorization;
}
return config;
},
error => Promise.reject(error)
);
export default API;
And this is an example usage
getUserList() {
API.get('/userlist')
.then(response => {
this.setState({
userList: response.data
}, () => {
console.log(this.state.userList)
});
})
}
But now im confused because I dont understand how to use this with a post so I can pass some data to it, similar to this
axios({
method: 'post',
url: constants.urlBackend + "/register",
data: qs.stringify({ email, password }),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
})
But using the above object.
API.post('/user/update/'+this.state.rowId).then(response => {
//some sort of body {email,password}
})
Have you tried
API.post(
'/user/update/' + this.state.rowId, {
email,
password
}).then(response => {})

localstorage do note update JWT Reactjs

This is the system flow:
I log in a save the user data in localstorage.
I got a component
that read the localStorage to get a user data, like JWT.
The problem is when I do a new login, the localStorage don't update with the new data and so I can't make requisitions that use the localStorage new user data.
I found that if I update manually the page, the localStorage it's udpdated.
In the reactjs I'm using react-router-dom to navigate with the pages.
How can I get new login data to update localStorage?
//login
api.post('users/login', {email, password})//make log in
.then(res => {
localStorage.removeItem('user_info');// I remove the ond data from localStorage
if(res){//If api do the post
let data = JSON.stringify(res.data.data)
localStorage.setItem('user_info', data);//Save new data in localStorage
history.push('/');//Go the homepage
}
}).catch(error => {
this.setState({ noAuth: true })
console.log('error');
});
The component that got the user data in localStorage:
import axios from "axios";
import { isAuthenticated } from '../../components/Util/Auth';
export const token = 'Z31XC52XC4';
// var user_info = JSON.parse(localStorage.getItem('user_info'));
// var auth_token = user_info.auth_token;
// console.log(isAuthenticated);
if (isAuthenticated()) {
var user_info = JSON.parse(localStorage.getItem('user_info'));
var auth_token = user_info.auth_token;
}
const api = axios.create({
// baseURL: 'https://url-from/api/', //PRODUÇÃO
baseURL: 'https://url-from/api/', //DESENVOLVIMENTO
headers: {
'Accept': 'application/json, text/plain, */*',
'Access-Origin': 'D',
'Authorization': `Bearer ${auth_token}`,
'Company-Token': `${token}`
}
});
// console.log(user_info);
api.interceptors.request.use(
config => {
console.log(config.headers);
console.log(user_info);
const newConf = {
...config,
headers: {
...config.headers,
'Authorization': `Bearer ${auth_token}`,
}
}
// return newConf;
},
error => Promise.reject(error)
)
export default api;
When you create an Axios instance you are passing in a "static" value.
'Authorization': `Bearer ${auth_token}`,
if this value doesn't exist, it becomes
'Authorization': `Bearer undefined`,
To fix it, you need to add an interceptor to axios to update the value of that token on EVERY request, not just on instance creation.
api.interceptors.request.use(
config => {
const user_info = JSON.parse(localStorage.getItem('user_info'));
const newConf = {
...config,
headers: {
...config.headers,
'Authorization': `Bearer ${user_info.auth_token}`,
}
}
},
error => Promise.reject(error)
)
I can do this using the tip of my friend JCQuintas
import axios from "axios";
import { isAuthenticated } from '../../components/Util/Auth';
export const token = 'Z31XC52XC4';
const api = axios.create({
// baseURL: 'https://url-from/api/', //PRODUÇÃO
baseURL: 'https://url-from/api/', //DESENVOLVIMENTO
headers: {
'Accept': 'application/json, text/plain, */*',
'Access-Origin': 'D',
// 'Authorization': `Bearer ${auth_token}`,
'Company-Token': `${token}`
}
});
api.interceptors.request.use(function (config) {
console.log(config);
if (isAuthenticated()) {
var user_info = JSON.parse(localStorage.getItem('user_info'));
var auth_token = user_info.auth_token;
}
config.headers.Authorization = `Bearer ${auth_token}`;
return config;
});
export default api;

Access vuex state in separate axios template js file

I have a problem. I have a Vuex state. Also I am making axios request. I have created a separate file for template axios request with predefined header. It looks like this:
import axios from 'axios'
import store from '../store/index'
export default axios.create({
baseURL: 'https://k-3soft.com/',
timeout: 1000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${store.getters.getToken}`
}
})
The problem is that in this case store in undefined. So how can I import to this /src/axios/request.js file my vuex store?
Also I have tried import { store } from '../store/index'.
My store looks like this:
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
Vue.use(Vuex)
export default new Vuex.Store({
namespaced: true,
modules: {
user
},
state: {
url: 'https://icfprod.k-3soft.com/',
token: '',
},
getters: {
getToken: state => state.token
},
})
Also may by anyone can share to view any repository where there is Vuex with modules, axios with file with separate predefined template. Just wanna see how to organize my project's structure. Thanks everyone for help.
Use a factory function to create the axios instance.
// request.js
import axios from 'axios'
const createAxiosInstance = (token) => {
return axios.create({
baseURL: 'https://k-3soft.com/',
timeout: 1000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
}
})
export default createAxiosInstance
Then use it in a module like:
// user.js
import createAxiosInstance from '../request.js'
const userModule = {
// ...
actions: {
async doSomeAction ({ state, commit, rootState }) {
const axios = createAxiosInstance(rootState.token)
const response = await axios.post('/some/api/endpoint')
.then(response => response)
.catch(error => {
// handle error
})
commit('SOME_MUTATION', response.data)
}
}
}

Categories