I am setting default headers in my vue application, but when I load the app it show me error.
main.js?56d7:14 Uncaught TypeError: Cannot read property 'defaults' of undefined
Code
const token = sessionStorage.getItem("token");
if (token) {
Vue.prototype.$http.defaults.header.common["Authorization"] = token;
}
I made a working codepen based on your issue.
In your case, you need to create axios client.
Please check this codepen. https://codepen.io/endmaster0809/pen/VwaPGzr
let apiClient = axios.create({
baseURL: "https://jsonplaceholder.typicode.com",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
const token = "testtoken";
if (token) {
apiClient.defaults.headers.common["Authorization"] = token;
}
Vue.prototype.$http = apiClient;
Related
I have method being successfully called by a button in my Vue component:
methods: {
goTestMe() {
console.log(this.$store.state.lang+' 1')
let url = 'some api url'
let headers = { headers: { 'Content-Type': 'application/json' } }
this.$axios
.get(url, headers)
.then(function(response) {
console.log('here')
console.log(this.$store.state.lang+' 2')
})
The problem is that the output of this is:
en-us 1
here
When it should be:
en-us 1
here
en-us 2
Clearly, the reference to this.$store.state is failing in the then() handler of the axios call.
Why is this? How can I send data received by my axios request to the Vuex store?
when you add the callback in the normal function you can't access the global object so you need to change it to an arrow function
methods: {
goTestMe() {
console.log(this.$store.state.lang+' 1')
let url = 'some api url'
let headers = { headers: { 'Content-Type': 'application/json' } }
this.$axios
.get(url, headers)
.then((response) => { // change it to arrow function
console.log('here')
console.log(this.$store.state.lang+' 2')
})
}
how can i set const value using mobx obeserve data? as i don't know how can i define props here.
export const BASE_URL = base_url_from_mobx
i have some data in this function. From there i will have some confidential data and a base url. This ApiKeys is a native module
ApiKeys.getApiKeys((data)=>{
let secureData = JSON.parse(data)
}
i have an api.js file where i set the interceptor and set the base url like below
const api = axios.create({
baseURL: BASE_URL,
timeout: 10 * 1000,
headers: {
'content-type': 'application/json',
}
});
here BASE_URL is defined and export as const in constants.js file but now i want to set it from the value i have got from the function.
This can be done if i can do like below
const api = axios.create({
// baseURL: BASE_URL,
baseURL: (JSON.parse(AsyncStorage.getItem(SECURE_KEY))).SOHOJ_APP_API_BASE_URL_DEVELOPMENT,
timeout: 10 * 1000,
headers: {
'content-type': 'application/json',
}
});
but it is giving me issue like
how can i do that. my i use to make a request like below using api.js
api
.post('api_end_point',parameters,headers)
.then(response=>{
})
.catch(error =>{
})
thanks
It means that there is some issue with your AsyncStorage.getItem(SECURE_KEY) ,probably it's not a proper json object.do a console.log of AsyncStorage.getItem(SECURE_KEY) and see what value you get.
I just started learn React but I have problem when I trying to make a request to the CoinMarketCap API with axios and tried several ways to set my API key. I have also also tried on Postman but message appears API key missing.
export const apiBaseURL = 'https://pro.coinmarketcap.com';
Tried like this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`,
{ headers =
{ 'X-CMC_PRO_API_KEY': 'apicode', }
})
this
dispatch({ type: FETCHING_COIN_DATA })
let config = { 'X-CMC_PRO_API_KEY': 'apicode' };
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`, { headers: config })
and this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?X-CMC_PRO_API_KEY=apicode`)
Thank you
The short answer to adding an X-Api-Key to an http request with axios can be summed up with the following example:
const url =
"https://someweirdawssubdomain.execute-api.us-east-9.amazonaws.com/prod/custom-endpoint";
const config = {
headers: {
"Content-Type": "application/json",
},
};
// Add Your Key Here!!!
axios.defaults.headers.common = {
"X-API-Key": "******this_is_a_secret_api_key**********",
};
const smsD = await axios({
method: "post",
url: url,
data: {
message: "Some message to a lonely_server",
},
config,
});
Adding the key to the default headers was the only way I could get this to work.
Use CMC_PRO_API_KEY as a query parameter, instead of X-CMC_PRO_API_KEY:
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?CMC_PRO_API_KEY=apicode`)
I realize this has been solved; for the sake of alternatives here is how I did it. I created a instance of axios in /includes/axios:
import axios from "axios";
const instance = axios.create({
baseURL: "https://example.com/api",
headers: {
"Content-Type": "application/json",
"x-api-key": "****API_KEY_HERE****",
},
});
export default instance;
Now axios can be imported anywhere in the project with the give configuration. Ideally you want to add your secret to the ENV variable for security reasons.
Inside React Native with Axios I'm making a request using axios to a remote url. I keep getting this error if I try to make the request.
The file “Macintosh HD” couldn’t be opened because you don’t have permission to view it.
Here's some of my code:
// inside componentDidLoad()
ExampleService.index().then(response => {
console.log('service response: ',response);
})
// in side ExampleService.js
function index() {
return client({
url: `/`,
method: 'GET'
});
}
// inside client
const client = axios.create({
baseUrl: 'http://192.168.42.64:3000',
headers: {
// 'Authorization': authHeader,
'Content-Type': 'application/json'
}
});
I finding way to config Axios globally with Authenticated in NuxtJS - VueJS (I use mainly NUXTJS).
All I need is: If user logged in and have token in $store, axios will get this token. If user is anonymous, axios wont get this token
~/plugins/axios
import axios from 'axios'
import AuthenticationStore from '~/store'
var api = axios.create({
baseURL: 'http://localhost:8000/api/v1/',
'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}
})
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': AuthenticationStore.state.token ? 'JWT ' + AuthenticationStore.state.token : ''
}
return config
}, function (error) {
// Do something with request error
return Promise.reject(error)
})
export default api
~/store/index.js
const AuthenticationStore = () => {
return new Vuex.Store({
state: {
token: null
},
mutations: {
SET_TOKEN: function (state, token) {
state.token = token
instance.defaults.headers = { Authorization: 'Bearer ' + token }
}
},
actions: {
....
}
})
}
export default AuthenticationStore
Error: [nuxt] Error while initializing app TypeError: Cannot read property 'token' of undefined
I would suggest to use interceptor instead which is more flexible and getting token when making request not on creation. Try something like that to avoid issues with not set token.
// ~/plugins/axios
import axios from 'axios'
import AuthenticationStore from '~/store'
var api = axios.create({
baseURL: 'http://localhost:8000/api/v1/',
'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}
})
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': AuthenticationStore.state.token ? 'Bearer ' + AuthenticationStore.state.token : ''
}
return config
}, function (error) {
// Do something with request error
return Promise.reject(error)
})
export default api
If you need to have no auth header, you need to add if at the begging of the interceptor.
Issue with your store:
You are exporting function when you should export instance of store,
so this is wrong:
const AuthenticationStore = () => {
You should export instance so:
const AuthenticationStore = new Vuex.Store({ ...
Please visit https://vuex.vuejs.org/guide/ to get better understanding. It is not bad that you don't understand it fully! Modules/instances/exporting in JS is not really easy to understand fully. Just try to learn it more. Good luck.