How to call axios from other folder - javascript

I want to create new folder name services in that folder will include all axios action and I'm using vue here. Heres what I try..
my save function
save() {
const CaseController = require("../services/gantt");
CaseController.create(this.data);
},
my service file
const axios = () => import("../plugins/axios");
exports.create = async () => {
return axios
.get("/")
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
.finally(() => {});
};
my plugins file
import axios from "axios";
export default axios.create({
baseURL: process.env.VUE_APP_API_URL,
headers: {
"Content-Type": "application/json",
},
});
but when I try, I got an error
Uncaught (in promise) TypeError: axios.get is not a function

Well, you've defined axios as () => import("../plugins/axios");, so it's a function, which does not have a .get method. Further, using import as a function makes it return a promise. You need to do:
const axios = import("../plugins/axios");
exports.create = async () => {
return (await axios)
.get("/")
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
.finally(() => {});
};

i solve this with
const axios = require("axios");
const instance = axios.create({
baseURL: process.env.VUE_APP_API_URL,
headers: {
"Content-Type": "application/json",
},
});
exports.create = async () => {
instance
.get("/")
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
.finally(() => {});
};
so, instead import the axios from plugins folder, use it directly from services

Related

TypeError: res.send is not a function with axios

everybody, I'm obtaining the following error:
TypeError: res.send is not a function
Why is this happening?
exports.obtainToken = () => {
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
axios
.post('***',{
client_id: '***',
client_secret:'***',
grant_type: 'client_credentials'
},
config)
.then(res => {
result = res.data;
console.log(res.data)
res.send(res.data)
})
.catch(error => {
console.error(error)
})
}
In this file, the import is:
const axios = require('axios');
I've not imported express. Is that the problem? How could I solve?

I am making a CRUD web application in React using axios. I'm getting the following error: "TypeError: Object(...) is not a function"

ERROR:
TypeError: Object(...) is not a function
Here is my code:
api.js file
import axios from "axios";
//url call to the server
const baseUrl = "http://localhost:9000/postmessages";
export default {
postMessage(url = baseUrl) {
return {
fetchAll: () => axios.get(url),
fetchById: (id) => axios.get(url + id)
}
}
}
and here is the postMessage.js file
//import api module
import api from "./api";
//fetchall records with a get request
export const fetchall = () => (dispatch) => {
api()
.postMessage()
.fetchall()
.then((res) => {
console.log("postMessage api");
dispatch({
type: ACTION_TYPES.FETCH_ALL,
payload: res.data,
});
})
.catch((err) => console.log(err));
};
what am i doing wrong or is there any alternative way which is better than what i'm doing
in your api.js you're exporting an object :
export default { //this is an exported object not function
...
}
then you're calling it as function using (), so you've to remove them and use it like :
api.postMessage()...
detailed :
//import api module
import api from "./api";
//fetchall records with a get request
export const fetchall = () => (dispatch) => {
api // omit the ()
.postMessage()
.fetchall()
.then((res) => {
console.log("postMessage api");
dispatch({
type: ACTION_TYPES.FETCH_ALL,
payload: res.data,
});
})
.catch((err) => console.log(err));
};

not able to catch error in axios react.js

I am making API call using axios in reactjs project but somehow I am not able to catch the error. I am getting 404 but not able to catch it. can somebody tell me what's wrong?
abc.js
export default axios.create({
baseURL: `my_base_url`,
headers: {
"Content-Type": "application/json",
},
});
xyz.js
export const createProcessApiCall = (param) => {
return API.post("/v1/process1", param);
};
zzz.js
const postData = async (param) => {
await createProcessApiCall(param)
.then((response) => {
setApiData(response.data.data);
setIsSuccess(response.data.isSuccess);
})
.catch((e) => {
setIsError(true);
});
};
you are combinining async code with sync code, try to use either asynchron :
const postData = async (param) => {
try {
const result = await createProcessApiCall(param)
}
catch(err) {
setIsError(true);
}
};
Or synchron :
const postData = (param) => {
createProcessApiCall(param)
.then((response) => {
setApiData(response.data.data);
setIsSuccess(response.data.isSuccess);
})
.catch((e) => {
setIsError(true);
});
};
Any status code different the sequence included between 200-299, you need to get at catch:
const postData = async (param) => {
await createProcessApiCall(param)
.then((response) => {
setApiData(response.data.data);
setIsSuccess(response.data.isSuccess);
})
.catch((e) => {
// #TODO parse err
console.log(e.response);
setIsError(true);
});
};
axios.interceptors.response.use(res=>{return res}, (error) => {
if (error.response.status !== 401) {
throw error;
}
if (typeof error.response.data.error.name !== "undefined") {
//do something on the error
}
});
its better to use axios interceptor to catch the error

How I can send my axios response to a variable with node.js

In fact, I begin with node.js. And i don't know how to pass the response to a variable. I don't want to make my code in my "response".. I try a lot of things but nothing is working.. I know is a simple question.. but it's not working
const axios = require('axios');
var test = null
function getLeagues () {
axios.get('https://api-football-v1.p.rapidapi.com/v2/fixtures/league/525?timezone=Europe/Paris', {
headers: {
'X-RapidAPI-Key': '<my-api-key>'
}
})
.then(response => {
test = response.data.api.fixtures
return response.data.api.fixtures
})
.catch(error => {
console.log(error);
});
}
console.log(test)
You should use promises and wait for the response to be ready:
const axios = require('axios');
function getLeagues () {
return axios.get('https://api-football-v1.p.rapidapi.com/v2/fixtures/league/525?timezone=Europe/Paris', {
headers: {
'X-RapidAPI-Key': 'foo-api-key'
}
})
.then(response => {
return response.data.api.fixtures
})
.catch(error => {
console.log(error);
return Promise.reject(error);
});
}
getLeagues().then(response => {
console.log(response);
});
Or, using async/await:
const consoleLeagues = async () => {
const leagues = await getLeagues();
console.log(leagues);
};
consoleLeagues();

Unhandled rejection when importing string constants rather than declaring them locally

I have a React-Redux thunk action that retrieves categories from an API server then adds them to the Redux store:
(categoryActions.js)
export const fetchCategories = () => dispatch => (
CategoryAPI.getCategories().then(categories => {
for(const category of categories) {
const {name, path} = category
dispatch(addNewCategory(name,path))
}
})
)
It works fine when using it with the following API call:
(categoryApi.js)
const apiServerURL = "http://localhost:3001"
const headers = {
'Content-Type': 'application/json',
'Authorization': 'whatever-you-want'
}
export const getCategories = () => (
fetch(`${apiServerURL}/categories`, { headers })
.then(res => res.json())
.then(data => data.categories)
)
However, when I try to define the API constants in a different file like so:
(apiConstants.js)
export const HEADERS = {
'Content-Type': 'application/json',
'Authorization': 'whatever-you-want'
}
export const SERVER_URL = "http://localhost:3001"
and then use them in categoryApi.js:
import {
HEADERS,
SERVER_URL
} from './apiConstants'
export const getCategories = () => (
fetch(`${SERVER_URL}/categories`, { HEADERS })
.then(res => res.json())
.then(data => data.categories)
)
I get the following error from line 3 of the thunk action in categoryActions.js above:
Unhandled Rejection (TypeError): Cannot read property
'Symbol(Symbol.iterator)' of undefined
What's the problem?
The problem is your variable is capitalized, so you need to set the property correctly, because fetch expects it lowercase:
export const getCategories = () => (
fetch(`${SERVER_URL}/categories`, { headers: HEADERS })
.then(res => res.json())
.then(data => data.categories)
)
--
{ headers }
is equivalent to:
{ headers: headers }
So in your second example you have it capitalized:
{ HEADERS: HEADERS }
This is known as property shorthand

Categories

Resources