I need help please. I'm working on a react-native app and I've been stuck here for a week.Whenever I tried getting a request I get the response as expect but when I tried to make a POST request in form-data form, or in json form to any endpoint I got weird errors from Axios in the react-native app. I tested the same endpoint on a create-react-app using axios and it seems to work fine but I can not receive the same feedback with react-native and axios.
this is my first approach
...//making the api call to /beneficiary endpointtry { const res = await axios({ url: '/beneficiary', method: 'POST', }); if (res.status === 200) { toast.success('User created!'); reset({index: 0, routes: [{name: 'drawer_nav'}]}); }} catch (error: any) { console.log(JSON.stringify(error))}
SO I try this approach
try { const res = await axios.post('/beneficiary', data, { headers: {'Content-Type': 'multipart/form-data', }, }); if (res.status === 200) { toast.success('User created!'); reset({index: 0, routes: [{name: 'drawer_nav'}]}); } } catch (error: any) { console.log(JSON.stringify(error)); }
Then the error changes to this
I dig and find out axios have be having issues Like this so I found another method of approaching it by intercepting resquests and responses.So I tried this approachI create a file call axios instance and place this configs in it
import axios from 'axios';import {base_url as baseURL} from './apis/endpoints';const axiosInstance = axios.create({ baseURL,});axiosInstance.defaults.headers.post['Content-Type'] = 'multipart/form-data';// Add a request interceptoraxiosInstance.interceptors.request.use( function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); });// Add a response interceptoraxiosInstance.interceptors.response.use( function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); });export default axiosInstance;
then I went back to the file I'm making the api requests to post form-data and use the axios instance I have.This is how I call it this time around
try { const res = await axios.post('/beneficiary', data); if (res.status === 200) { toast.success('User created!'); reset({index: 0, routes: [{name: 'drawer_nav'}]}); }} catch (error: any) { console.log(JSON.stringify(error))}
and I'm still receiving errors
I'm stuck. I don't know what else to try. Its working fine using reactjs.react-native version 0.70.0axios version ^1.2.1(using typescript)