how can i add headers in vue js using async/await - vue.js

i'm trying to send a request to the backend which uses headers, please how can i add the headers
this is my script tag
<script>
import axios from "axios";
export default {
data: () => ({
fullName: "",
streetAddress1: ""
}),
created() {
//user is not authorized
if (localStorage.getItem("token") === null) {
this.$router.push("/login");
}
},
methods: {
async onAddAddress() {
const token = localStorage.getItem("token");
headers: {
"Content-Type": "application/json",
Authorization: "Bearer" + token,
"x-access-token": token
}
try {
let data = {
fullName: this.fullName,
streetAddress: this.streetAddress1
};
const response = axios
.post("http://localhost:5000/api/addresses", data)
.then(res => {
console.log(res);
});
console.log(response);
} catch (error) {
console.error("error >>", error);
}
}
}
}
this code gives me an error, please how can i go about this

There are a few problems with your code. For instance you do not define headers as a variable and you do not add it to your axios request as a third argument. I think you need something like this:
async onAddAddress() {
const token = localStorage.getItem("token");
/// define headers variable
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer" + token,
"x-access-token": token
};
let data = {
fullName: this.fullName,
streetAddress: this.streetAddress1
};
try {
/// config as the third argument.
conts result = await axios.post("http://localhost:5000/api/addresses", data, { headers });
console.log(result);
}
catch (error) {
console.error("error >>", error)
}
}
For async/await to work, you need to add await in front of the axios call.
Hope this helps.

Related

How to set authorization header coorectly?

Problem:
In my react native app in order to remove repeated calls I have developed a general POST GET methods in httpClient file. It code is look likes this.
import axios from 'axios';
import AsyncStorage from '#react-native-community/async-storage';
axios.defaults.headers.post['Content-Type'] = 'application/json';
var instance = null;
const setAuthorisationHeder = async () => {
const token = JSON.parse(await AsyncStorage.getItem('auth_data'));
if (token) {
console.log('>>>>>> instance', instance);
Object.assign(instance.headers, {
Authorization: 'Bearer' + token.accessToken,
});
} else {
console.log('>>>>>> instance', instance);
Object.assign(instance.headers, {
Authorization: '',
});
}
};
export const setHeader = () => {
console.log('>>>>>>>> HIIII');
instance = axios.create({
baseURL: '',
timeout: 150000,
headers: {
'Content-Type': 'application/json',
},
});
instance.interceptors.response.use(
function (response) {
return response;
},
async function (error) {
if (error.response.status) {
if (error.response.status === 401) {
AsyncStorage.removeItem('auth_data');
} else {
throw error;
}
} else {
console.log(error);
}
},
);
};
export const Get = (route, data) => {
function getData() {
return instance.get(
route,
data == null ? {data: {}} : {data: JSON.stringify(data)},
);
}
if (instance) {
console.log('>>>>>> HIIIIii');
// setAuthorisationHeder();
return getData();
}
return setHeader().then(getData);
};
export const Post = (route, data) => {
console.log('>>>>>> route', route);
function postData() {
return instance.post(route, JSON.stringify(data));
}
if (instance) {
console.log('>>>>>> HIIIIii');
// setAuthorisationHeder();
// setAuthorisationHeder();
return postData();
}
return setHeader().then(postData);
};
Can some tell me a way to add an authorization header to this instance? My token is storing the Asyncstorage in the middle of some actions so at the beginning called I don't have the token. As my code setHeader is running only one time so I created a method call setAuthorisationHeder() function. But it is giving me can not find property .then error when I am putting a request. Can someone help me to solve this issue? Thank you?
you can define global headers once and use it in every network call.
https://github.com/axios/axios#global-axios-defaults
Create a global auth variable where you'll store the auth data from storage. Before making a request get the auth data and use interceptor to set the bearer token.
let authToken = '';
const getAuthToken = async () => {
// asumming auth token was saved as string
authToken = await AsyncStorage.getItem('auth_data');
};
Interceptor
// request interceptor
axiosInstance.interceptors.request.use(
function (config) {
// Do something before request is sent
config.headers.Authorization = `Bearer ${authToken}`;
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
complete code
import axios from 'axios';
import AsyncStorage from '#react-native-community/async-storage';
let authToken = '';
const axiosInstance = axios.create({
baseURL: '',
timeout: 150000,
headers: {
'Content-Type': 'application/json',
},
});
// request interceptor
axiosInstance.interceptors.request.use(
function (config) {
// Do something before request is sent
config.headers.Authorization = `Bearer ${authToken}`;
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
const getAuthToken = async () => {
// asumming auth token was saved as string
authToken = await AsyncStorage.getItem('auth_data');
};
export const Get = async (route, data = {}) => {
// get and set auth token
await getAuthToken();
// route = /user?id=787878 or /user/787878
return await axiosInstance.get(route);
};
export const Post = async (route, data = {}) => {
await getAuthToken();
return await axiosInstance.post(route, data);
};

How to set token into onError ApolloClient?

I want to handle error if return error will call setContext for query again but I can't get token in local state because onError does not accept async. How I can do that.
Thanks
//
export default async () =>
new ApolloClient({
cache: new InMemoryCache({
dataIdFromObject: object => object.key || null
}),
uri: Api.GRAPH_QL_URL,
clientState: { defaults, resolvers },
// cho handle network failed
///onError not accept async
onError: ({ graphQLErrors, networkError, operation, forward }) => {
// how to get token in hear
if (networkError) {
operation.setContext({
headers: {
Accept: "application/json",
authorization: token !== null ? `JWT ${token}` : "" // how to put token into authorization
}
});
}
},
// Call query
request: async operation => {
const token = await AsyncStorage.getItem(strings.keyToken);
console.log("Client request: ", {
operationName: operation.operationName,
variables: operation.variables,
query: operation.query,
jwtoken: token
});
operation.setContext({
headers: {
Accept: "application/json",
authorization: token !== null ? `JWT ${token}` : ""
}
});
},
});
//I want to handle error if return error will call setContext for query again but I can't get token in local state. How I can do that.
Thanks
You need to set an Observable in order to work with async/await inside the onError method.
Import it from apollo-link (import { Observable } from 'apollo-link';).
onError: ({ graphQLErrors, networkError, operation, forward }) => {
if (networkError) {
return new Observable(async (observer) => {
const token = await AsyncStorage.getItem(strings.keyToken);
const headers = operation.getContext().headers;
operation.setContext({
headers: {
...headers,
Authorization: token !== null ? `JWT ${token}` : ''
}
});
const subscriber = {
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
};
return forward(operation).subscribe(subscriber);
});
}
}

Using Axios GET with Authorization Header in vue App

I'm trying to use axios for a GET request with an API which requires an Authorization header.
here is my current code
My current code:
data () {
return {
listings: [],
AuthStr : 'Bearer ' + JSON.parse(localStorage.getItem('token')),
}
},
created () {
axios.get(`url`, { 'headers': { 'Authorization': AuthStr } })
.then((response => {
this.listings = response.data;
})
.catch((error) => {
console.log(error)
})
}
it shows me 403 error I don't know why.
There are several ways to to add header to request.
For a single request:
let config = {
headers: {
Authorization: value,
}
}
axios.get(URL, config).then(...)
you need to call data().AuthStr to get your token there is a typo.
Your created function will be
created () {
axios.get(`url`, { 'headers': { 'Authorization': data().AuthStr } })
.then((response) => {
this.listings = response.data;
})
.catch((error) => {
console.log(error)
})
}
It should be:
axios.get(`url`, { 'headers': { 'Authorization': this.AuthStr } })
You are using JSON.parse when getting the value for AuthStr. JSON.parse returns an object. Try removing it and if you are using the correct Auth token, it should work.

Vue axios changing Auth Headers with an interceptor

I am new to vue and stuck on this problem for quite some time. I have a login method that retrieves an API token and stores it in localStorage. The login API call is the only call that does not send Auth headers. After the Login every call should add the API token to the header.
When I login the interceptor does not set the new header. It needs a page refresh in the browser to work. Why is that, what am I doing wrong?
In my Login component I have this method:
methods: {
login() {
api.post('auth/login', {
email: this.email,
password: this.password
})
.then(response => {
store.commit('LOGIN');
localStorage.setItem('api_token', response.data.api_token);
});
this.$router.push('reservations')
}
}
Additionally I have this axios base instance and an interceptor:
export const api = axios.create({
baseURL: 'http://backend.local/api/',
// headers: {
// 'Authorization': 'Bearer ' + localStorage.getItem('api_token')
// },
validateStatus: function (status) {
if (status == 401) {
router.push('/login');
} else {
return status;
}
}
});
api.interceptors.request.use((config) => {
config.headers.Authorization = 'Bearer ' + localStorage.getItem('api_token');
return config;
}, (error) => {
return Promise.reject(error);
});

Axios interceptors - Not using instance until AsyncStorage resolved?

I've an Axios Interceptor setup to manage responses and cut down on re-writing code everywhere. Currently, I need to add the Authorization header using the { config } object in each call like below.
apiCall = () => {
const token = await AsyncStorage.getItem('JWT_BEARER_TOKEN');
const config = {
headers: {
'Authorization': 'Bearer ' + token,
}
}
const attendance = await axiosInstance.post('/team/matchday', data, config);
// ... do something with attendance
}
I'd like to do it in the axiosInstance I've create as below, but I'm getting a promise rejected error. I presume this is because token is still an incomplete promise when it is returned.
Any ideas how to handle this config correctly?
import { AsyncStorage, Alert } from 'react-native';
import axios from 'axios';
const ReturnAxiosInstance = async (token) => {
const AxiosInstance = axios.create({
baseURL: 'http://localhost:4000',
timeout: 3000,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + await AsyncStorage.getItem('JWT_BEARER_TOKEN'),
},
});
AxiosInstance.interceptors.response.use(
response => response,
(error) => {
if (!error.response) {
Alert.alert('Network Error!');
return console.log(error);
// return dispatch({ type: 'NETWORK_FAILURE' });
} else if (error.response.status === 500) {
Alert.alert('Server Error!');
} else if (error.response.status === 404) {
Alert.alert('Endpoint doesn\'t exist!');
}
// handle the errors due to the status code here
return error.response;
},
);
return AxiosInstance;
};
export default ReturnAxiosInstance();
You need to add in the request interceptor for your Axios instance.
// ...
axiosInstance.interceptors.request.use(
async (config) => {
config.headers.authorization = await AsyncStorage.getItem('JWT_BEARER_TOKEN');
return config;
},
error => Promise.reject(error)
);
// ...