NuxtJS - manage several axios instances - vue.js

I use NuxtJS 2, and I need to have 2 or more axios instances with different configs.
In VueJS / JS classic, I can just create a new instance of axios:
var axiosElasticSearch = axios.create({
baseURL: 'https://elastic.com/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
But in Nuxt, they apply their own config to handle this, because of the SSR layer.
In my Nuxt config, I have this :
axios: {
baseUrl: process.env.API_URL,
browserBaseUrl: process.env.BROWSER_API_URL,
withCredentials: true,
headers: {
common: {
Accept: 'application/json',
Authorization: 'Bearer ' + process.env.API_TOKEN
}
}
},
And then, I can inject it easily.
Is it possible to manage it in Nuxt? I looked at proxy option, but I don't think it's what I want.

nuxt/axios allows creating new Axios instances with $axios.create, which takes the Axios config from nuxt.config.js into account.
For example, you could create a Nuxt plugin that injects a new Axios instance into the root context:
// ~/plugin/api.js
export default function ({ $axios }, inject) {
// Create a custom axios instance
const api = $axios.create({
headers: {
common: {
Accept: 'text/plain, */*'
}
}
})
// Set baseURL to something different
api.setBaseURL('https://my_api.com')
// Inject to context as $api
inject('api', api)
}
And configure your Nuxt app to use it:
// nuxt.config.js
export default {
plugins: ['~/plugins/api.js']
}
Then your component could use the new Axios instance:
// MyComponent.vue
export default {
fetch() {
this.$api.get(...)
},
asyncData({ $api }) {
$api.get(...)
}
}

Related

Axios not sending cookies in the headers, even using withCredentials: true | Backend FastAPI

My axios config
Using postman I get the cookie just fine, so it's an axios problem.
const api = axios.create({
baseURL: 'http://localhost:8000/',
withCredentials: true,
headers: { crossDomain: true, 'Content-Type': 'application/json' },
})
export default boot(({app}) => {
// for use inside Vue files (Options API) through this.$axios and this.$api
app.config.globalProperties.$axios = axios
// ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
// so you won't necessarily have to import axios in each vue file
app.config.globalProperties.$api = api
// ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
// so you can easily perform requests against your app's API
})
export { axios, api }
const response = await api.get(
'',
)
What am I missing here?
You can't send cookie of localhost any other hostname or ip you can send just different subdomain.
You need same site parameter.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#samesite_attribute

Vue Dynamic URL From state. In axios call

I want to parse the axios url call from a variable state in vuex. As simple as this:-
state: {
getOrganizationURL: "opensource",
}
actions: {
getOrganizationDashboard({commit, state}) {
axios
.get(`"https://xxx/api/report/"${state.getOrganizationURL}`, {
headers: {
Authorization: `Bearer ${state.currentAuthToken}`,
},
})
.then(response => {
commit("setOrganizationsDashboardData",response.data)
});
},
}
when checking the network on the browser. The API call is going to a weird url instead.
e.g
Request URL: http://localhost:8080/%22https://xxxx/api/report/%22opensource
which leads to page not found...
I think it a minor mistake. Any tips please?

set mobx store in const value in react native

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.

Access to XMLHttpRequest at 'https://***' from origin 'http://localhost:3000' has been blocked by CORS policy

I'm trying to send a request with axios but I have CORS problem,
this is my nuxt.config.js
plugins: [
"#/plugins/axios/apiService.js",
],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
],
axios: {
baseURL: process.env.API_URL,
proxy: true,
credentials: false
},
proxy: {
'/api': {
target: 'https://dev.mobit.ir/api/web/v4',
pathRewrite: {
'^/api' : '/'
},
changeOrigin: true,
}
},
and this is my apiService
import axios from "axios";
import { API_URL} from "./config";
export const axiosInstance = axios.create({
headers: {
Accept: 'application/json',
}
});
//Set base url for axios requests
axiosInstance.defaults.baseURL = API_URL;
export const ApiService = {
//resource: api address
get(resource, params = "") {
return axiosInstance.get(resource, {params}).catch(error => {
throw new Error(`[RWV] ApiService ${error}`);
});
},
post(resource, params) {
return axiosInstance.post(`${resource}`, params);
}
};
I tried to set proxy according to nuxt documentation but it doesn't work,
If I use a proxy like https://cors-anywhere.herokuapp.com/ it will works but what why nuxt proxy doesn't work? and I think it's not the correct way.
Do I have to use cookie or middleware?
according to the link below, we should use an array in our module's array for defining proxy like this:
['#nuxtjs/proxy', { pathRewrite: { '^/api' : '/api/web/v4' } }]
link to read more:
https://github.com/nuxt-community/proxy-module
In this type of CORS problems using extensions like link below can solve it until publish it in main domain
https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en#:~:text=Allow%20CORS%3A%20Access%2DControl%2DAllow%2DOrigin%20lets%20you,default%20(in%20JavaScript%20APIs).

Put API KEY in axios

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.