Creating an instance of axios in Vue not working - javascript

I am using axios for AJAX in Vue. In the article written by You, he mentioned that we can set Vue.prototype.$http = axios and I can use this.$http in Vue instance. It works fine.
However, if I want to create an axios instance to $http, like
Vue.prototype.$http = axios.create({
baseURL: 'https://app.herokuapp.com/'
})
It does not work when I use this.$http.get('/relativeURL'). It seems that it cannot access the config I set. That is, it will not send request to https://app.herokuapp.com/relativeURL
In another way, if I set axios instance in any other object, such as Vue.prototype.$axios = axios.create({config}). It works successfully.
Could someone explain why this happen ??

While defining it at Vue instance level might have its own merit, I don't like to pollute the global namespace. What my approach is, I have a gateway folder, where I have different files for axios instance, such as:
backend-api.js
import axios from 'axios'
export default axios.create({
baseURL: 'http://YourAPiIp:9090/api/v1',
timeout: 100000,
headers: {
'Content-Type': 'application/json'
}
})
Now you can import it the place you want and use it:
import backendApi from '../../gateways/backend-api'

You set
Vue.prototype.$https = axios.create({
baseURL: 'https://app.herokuapp.com/'
})
And use
this.$http...
Typo in property name (https vs http).
Leave it as $http. Or simply don't even declare $http if it misleads you - use just this.axios.get...

Related

I am getting error axios.default.create is not function with webpack and react-cra

We have created a custom javascript library called Domain and we are using Axios to hit API calls inside that library. we gave app-domain name in package.json and axios as dependencies also.
import axios from "axios";
export class Domain {
axiosInst: any;
constructor() {
console.log('axios -->', axios);
this.axiosInst = axios.create({
baseURL: config.baseUrl,
headers: {
'Content-Type': 'application/json'
}
});
}
}
Now, If we use this custom library in our node application (we are adding app-domain in node package.json dependencies) we are able to use this Domain class properly and can hit the API's also.
But if we use the same thing in our react (CRA) application we are getting an below error.
Uncaught TypeError: axios_1.default.create is not a function
After some debugging we found that in Node application we are getting actual axios object but during react application we are getting
console.log('axios -->', axios);
/static/media/axios.d3b7d28587da77444af0.cjs
So Webpack is considering Axios as assets and creates a file for that which we don't need.
Does anyone have any idea how to solve this issue?

axios instance not working as expected in React.js

I have a component called Login.js There I import Axios libray normal way and it works like this.
import axios from 'axios';
const data = await axios.post('/user/login/', {
email: e.email,
password: e.password,
});
Getting 404 is fine because I didn't set any base URL for the Axios. Please note all the requests, response headers here.
Then I try to created Axios instance inside a lib folder and import it like this
/src/lib/axios.js
import axios from "axios";
const baseUrl = process.env.REACT_APP_BE_URL;
const axiosInstance = axios.create({
baseURL: baseUrl,
});
export default axiosInstance;
I import this instance instead of normal Axios import.
import axios from 'libs/axios';
Now I see the request like this a lot of properties missing in the request and this isn't working
How do I fix this?
Any help thanks in advance.

How to import Nuxt modules inside a js file

What I'm trying to do is to import Nuxt modules inside a js file.
for example I want to use "#nuxt/axios" inside a js file and create an instance from it and I don't want to call it from context object I want to make that instance separate from any Nuxt life cycle and also use the nuxt axios modules not the normal axios package.
import axios from "#nuxt/axios"
const axiosInstace = axios.create();
export default axiosInstace;
Don't use these modules directly. #nuxt/axios is just a wrapper for the axios module. Just use that instead (NPM). Same goes for most other nuxt modules.
Just like what #Florian Pallas mentioned. Don't use these modules. use NPM or/and extend Axios from plugins
Edited answer:
I remember seeing this code somewhere
const myAPI = axios.create({
baseURL: 'https://api.domaine.com/',
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
params: {
order: 'desc',
sort: 'name'
}
})
function request(id) {
myAPI.get('/users/'+id);
}
request(123)

NPM run serve - LocalStorage already defined as a built-in global variable

Any example I downloaded which demonstrates the use of vue.js and axios runs into the following problem as I run 'npm run serve'
'localStorage' already defined as a built-in global variable
As I haven't changed anything in the code and the examples are used by many people, the error has to be on my side. It occurs wherever localStorage is used. The is no new declaration of it
import axios from 'axios'
const API_URL = process.env.API_URL || 'http://localhost:3000/api/v1'
export default axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.token
}
})

ReactJS - Importing store breaks Jest

I had a file with one function that creates an axiosInstance, it used to look like this:
import Axios from 'axios';
import getToken from '#/api/auth-token';
const [apiUrl] = [window.variables.apiUrl];
export const createApiInstance = () => {
return Axios.create({
baseURL: `${apiUrl}`,
headers: {
Authorization: `Bearer ${getToken()}`,
},
});
};
Something we wanted to implement was notifying the user when their JWT token expires (so they won't unwittingly continue using the app while all of their requests are returning 401s). My solution turned this file into this:
import Axios from 'axios';
import getToken from '#/api/auth-token';
import store from '#/main.jsx';
import { userActionCreators } from '#/store/action-creators';
const [apiUrl] = [window.variables.apiUrl];
export const createApiInstance = (urlExtension = '') => {
const axiosInstance = Axios.create({
baseURL: `${apiUrl + urlExtension}`,
headers: {
Authorization: `Bearer ${getToken()}`,
},
});
axiosInstance.interceptors.response.use(response => {
if (response.status === 401)
store.dispatch(userActionCreators.setUserTokenExpired());
return response;
});
return axiosInstance;
};
This worked very well, as now all of the responses from the API are being checked for a 401 Unauthorized status and dispatching an action so the app can respond to it.
Jest doesn't like the import store, so 95% of the tests in the app fail when the store is imported here. I'm certain it is the importing of the store because every test passes when it is commented it.
I've had absolutely no luck getting anything to work.
I've tried updating setting jest and babel-jest to the same versions, setting react, react-dom, and react-test-renderer to the same versions. I've looked into configuring moduleNameMapper to mock the store in the jest config in package.json but I'm not sure how to make that work. I'm starting to consider taking a completely different approach to this problem such as applying middleware to check for 401 responses instead, but I'm worried I'll end up running into the same issue after a bunch of work.
The problem with mocking the store in the test files themselves is that there's hundreds of test files in this large application, so literally anything besides adding mocking to each individual file is the solution I'm looking for.
If anyone else is having this problem, this occurred because I was exporting the store from the same file as my ReactDOM.render. Apparently you can export from this file but as soon as you try to import what is exported somewhere else it will catch it and break tests. The solution is to create and export the store from a different file.
Make sure you have a .babelrc file, as jest doesn't understand the context of babel and JSX files otherwise. Related Stack Qusetion
If that doesn't quite do the trick can you update with the main.jsx code and let me know then i'll update

Categories

Resources