How to ignore SSL issues in axios using React Native? - reactjs

Hi I'm currently working with react native on Android with Expo. I am trying to send requests to my server which has a valid ssl certificate, but for some reason axios takes it as invalid, so axios does not allow me to send requests to my server's api.
this is the error i get:
Error: Network Error
So I wonder if there is any way to make axios ignore the problem with the ssl and can send the requests in a normal way
this is my code:
try {
const headers = {
'Accept-Language': 'es-ES,es;q=0.8',
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
};
axios.get("https://URLtoMySERVER", {}, headers)
.then(response => {
console.log(response)
const posts = response.data;
console.log(posts)}
).catch(function(error) {
console.log("error", error);
});
} catch (error) {
console.log('err', error);
}
some points that I want to clarify:
1- I can't use RNFetchBlob because I'm using Expo, and RNFetchBlob have some native libraries.
2- I can't use httpsAgent either with axios because apparently https library does not work with expo, or at least it does not work for me.
3- fetch doesn't work either
Is there any other alternative to axios or fetch that works in react native with expo and where you can ignore the problems of https?

Related

React - Getting 401 authorization and CORs preflight error when trying to access a Kubernetes API endpoint using Axios

My React host has an IP of 10.60.160.61.
The API endpoint that I'm trying to reach has an IP of 10.200.50.21.
My App.js:
useEffect(() => {
const fecthPods = async () => {
try {
const response = await axios.get(`https://kubernetes.endpoint.com/k8s/clusters/name/v1/pods/myproject`,{ headers: { 'Authorization': 'Bearer token-myToken' } })
console.log(response.data)
} catch (err) {
if (err.response) {
// Not in the 200 response range
console.log(err.response.data)
console.log(err.response.status)
console.log(err.response.headers)
} else {
console.log(`Error: ${err.message}`)
}
}
}
fecthPods()
},[])
I get two errors in the network tab of developer tools:
401
CORS preflight
I can access an external API endpoint with no issue (ie. https://pokeapi.co/api/v2/pokemon/ditto).
I can successfully run a curl command to the Kubernetes API endpoint by passing the Auth token in the headers parameter, but just not working with Axios.
I don't think I need to run a backend express server since the API endpoint that I'm trying to reach is not on my localhost.
Not sure what else to try.
I believe I have found the answer to this question. Seems like I will need to run my API calls through a custom proxy as mentioned in this post.

Axios returns NetworkError / CORS Headers enabled

I build a ionic-react android application with Axios to get a server response. Two weeks ago my code was working fine. Now the axios request always returns a NETWORK_ERR (HttpError or Axios Error).
I tried to use all CORS Headers possible in my api, but the request is not sent to the webservice.
I hope anyone can help me:
This is the Code I was using:
const api = axios.create({
baseURL: "http://192.168.0.145:8080/RestFulTest-1.0-SNAPSHOT/api",
});
function callApi(){
api.get("/verification")
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
}
Just directly opening the API Url in browser is not loading it...
Sot it seems either the backend is down or blocking and requires an authorization header with the axios request, like
let tokenStr = "Your TOKEN";
axios.get("/verification", { headers: {"Authorization" : `Bearer ${tokenStr}`} });
Hope it helps..

Getting the React CORS preflight error in React Native

I am getting the CORS access error in my React Native app when connecting to an external API.
async componentDidMount() {
// POST request using fetch with async/await
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: JSON.stringify({ type:'accountLookup',storeId:STORE_ID, storeKey:STORE_KEY, memberId:'471324' })
};
const response = await fetch('http://frequent5.revlogical.com/wsMobile', requestOptions);
const data = await response.json();
this.setState({ data: data });
The problem is most likely not with React app, rather with your server which is not configurated to serve your app.
You should set 'Access-Control-Allow-Origin' header on your server to allow your app's address to make requests.
This problem is usually the fault of the backend. Test it with a tool like https://www.test-cors.org/
An alternative is to create a server to be intercepted between the frontend and the API, and you can handle this guy's cors

Cannot make a GET request in Postman with React

I created a joke generator app that takes jokes from a local json file with data that I created and displays it in the browser. This app has no backend at all. I am trying to make a GET request through Postman, but no luck. Is it even possible to use postman in this scenario?
NO Postman is not used for programmatic api calls. Use axios for this. Suppose your server is running on localhost:3000.
npm install axios
In your component,
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/jokes?id=1')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});

"Network Error" with Axios and DjangoREST but request succeeds at the end

So, I am using ReactJS and DjangoRESTframework to build my app.
Now..when I send a request with Postman it works perfectly(ex. 127.0.0.1:8000/api/users/ GET request) and when I try to do it in React with Axios I get a network error but on my local development server console I see that it succeeded.
This is my get request with axios in react:
componentDidMount() {
axios.get('http://127.0.0.1:8000/api/users/', {
headers: {
'Accept': 'application/json'
}
})
.then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
})
}
And I get an Network Error. But as I said with Postman it works.
One more example is that I send POST request with Axios to http://127.0.0.1:8000/api/users/ and as response I get Network Error as well but on my backend, user IS created.
This is code for my POST request with axios:
let formData = new FormData();
formData.set('email', this.state.emailField);
formData.set('username', this.state.usernameField);
formData.set('password', this.state.passwordField);
axios({
method: 'POST',
data: formData,
url: 'http://127.0.0.1:8000/api/users/',
config: {headers: {'Content-Type': 'multipart/form-data'}}
}).then(request => {
console.log(request.data);
}).catch(err => {
console.log(err);
})
I googled for about an hour to fix this but nothing helps.
Can you be more clear on what you see as Network error? Attach some error messages / Stack trace.
This looks like a Cross-Origin Resource Sharing (CORS)
issue to me. Try configuring CORS on your DjangoRESTframework backend.
This might help you if that is the case.

Resources