i have a configuration with axios i am testing a feature to receive a list of students from an api, the problem is that it sends me an error:
TypeError: constants_api_constants__WEBPACK_IMPORTED_MODULE_1_.default.interceptors.request is not a function
For my axios configuration I use:
JavaScript
x
21
21
1
const options.GET_ALL_STUDENTS = {
2
method: "GET",
3
url: "/Student",
4
}
5
const BASE_API_URL = "https://localhost:7072/api";
6
const api = axios.create({
7
baseURL: `${BASE_API_URL}`,
8
});
9
10
const getStudents = () => {
11
return api.interceptors.request(options.GET_ALL_STUDENTS).use(
12
function request(success) {
13
return success;
14
},
15
16
function error(err) {
17
return err;
18
},
19
);
20
};
21
How I resolve my promise, (without interceptor this work fine):
JavaScript
1
10
10
1
function* fetchStudents() {
2
try {
3
const result1 = yield call(getStudents);
4
const studentList = createStudentListAdapter(result1.data);
5
yield put(fetchStudentsSuccess(studentList));
6
} catch (error) {
7
yield put(fetchStudentsFailure());
8
}
9
}
10
Advertisement
Answer
Interceptors are used to intercept any request/response
before it goes to try/catch
.
JavaScript
1
9
1
const getStudents = async () => {
2
try {
3
const res = await api(options.GET_ALL_STUDENTS);
4
// logic
5
} catch (e) {
6
// handle error
7
}
8
};
9
Interceptor
JavaScript
1
11
11
1
api.interceptors.request.use(
2
(request) => {
3
console.debug("Request", request.url);
4
return request;
5
},
6
(error) => {
7
console.debug("Request Failed", error.request.data.message);
8
return Promise.reject(error);
9
},
10
);
11