Issue
I'm using axios to make requests to fetch the data from my external API (it's HTTP AWS server with ExpressJS and Nginx). I tested it on my local machine with the web version of my Ionic app and everything is working expected. Also I can fetch data if I'm using my phone's browser.
Same goes with postman, I can fetch data without any problems.
The only place where these requests don't work is the actual device. Looking at the Android Studio console the error is: "Msg: Network Error" (failing to figure out how to get more from axios error object).
I configured CORS following the official Ionic documentation. I've set all needed origins and options (can't use * origin because I have to use credentials with my requests). Express configuration looks like this:
const corsOptions = {
origin: [
'http://localhost:8100',
'http://localhost:8080',
'http://localhost',
'capacitor://localhost',
'ionic://localhost',
],
credentials: true,
optionsSuccessStatus: 200,
exposedHeaders: ["set-cookie"]
}
// Enable preflight requests for all routes
app.options('*', cors(corsOptions));
app.use(cors(corsOptions));
On the client (request example):
try {
const response = await axios('http://my.api.url', {
method: 'get',
withCredentials: true,
headers: {
'Accept': 'application/json'
}
});
const data = response.data;
// Do something with the data
} catch(error) {
console.log(error);
};
I think it has something to do with Capacitor, maybe there is a problem with non-https API (but then the question is why does it work with the web version). I tried disabling credentials for my requests but the error reoccur. Also removing Nginx doesn't seem to change anything.
Update: Also the axios says the request is sent but the server didn't respond.
Solution
I sorted it out, I had to do following.
Had to add a SSL to my web server (I used letsencrypt).
Had to add this to capacitor.config.json:
"server": { "allowNavigation": [ "my.api.url" ] }
Official Capacitor Documentation - Common Configuration
Answered By - Serjuice
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.