Network error with axios and android emulator - axios

I got a React-Native application working with a NodeJS backend which serves an API.
My React-Native front is using Expo and Axios to hit on a route of my NodeJS API (using Hapi, Joi, Knex), which will (for the example) update my DB (MySQL).
Everything works properly with my iOS simulator. However, on Android Emulator, SOME of my hits on route ""does not work"" with the following error message : Network Error - node_modules/axios/lib/core/createError.js:16:24 in createError (actually, it worked, but the front does not detect it...)
This is strange, because like I said, this is ONLY for some of my route. I changed the http://localhost:8000/api to http://10.0.2.2:8000/api to be sure that Android Emulator access my API, and it is ok for this part.
The buggy route is working properly on iOS, and is working properly on Insomnia / Postman ( localhost:8000/api/sendMail ). It is working on Android Emulator, but the application does not detect it.
This is an example of my code :
FRONT -- On press of my button "SendEmail" :
/* Button.js */
const sendAndEmailPromise = await sendEmail(this.state.email);
console.log(sendAndEmailPromise); // Output : NOTHING (not undefined, not null, N O T H I N G).
if (sendAndEmailPromise.status === 200) {
// handle it
} else (sendAndEmailPromise.status === 403) {
// etc. for each of my codeStatus that can be returned by my API
}
/* MyAPI.js */
export function sendEmail(mail) {
return axiosInstance
.post(`/sendEmail`, null, {
params: {
mail
},
})
.then(response => response) // Will not enter here
.catch(error => {
console.log(error); // Will output : NETWORK ERROR
});
}
BACK -- This is the sendEmail promise :
// Will return true of false :
const isMailSend = await sendTheEmail(mail);
console.log(isMailSend); // Output : TRUE and I receive the email on my gmail, so Android Emulator HIT the route.
if (isMailSend) {
return handler
.response({
data: {
message: "Email sent.",
},
})
.code(200);
} else {
// Handle it and return another response
}
I expect my front to now that everything works fine (which actually happened...) and get the code status of that, instead of a "Network error".
More, is it possible with Axios to get another level of error ? Something more specific.
A GitHub issue which is not totally the same but seems to relate something equivalent : https://github.com/axios/axios/issues/973
Thank you.

You are dealing with two problems here:
1) your emulator doesnt work because it cannot resolve the word "localhost" to an ip. is like using localhost2.com it will not resolve to something. This must be pointed to the local ip of your server 192.x.x.x
2) you server must be binded to 0.0.0.0 because by binding it to localhost it cannot resolve to local requests like 192.x.x.x. If you fix the binding your emulator would have the possibility to see the server and postman will too.

Adding these parameter in header resolved my issue
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"

Related

Is it possible to know that the error is CORS in Axios?

Axios gives us the interception ability. I have created a response interceptor to get errors.
This is my code:
const errorInterceptor = error => {
if (error.code === 'ERR_NETWORK') {
throw new Error('Network is not connected')
}
// The rest of the code
}
However, if I get the CORS error, I can't find any information to know that it was a CORS error.
Why do I need this?
I want to provide meaningful messages to my users.
If network is disconnected, I want to show You are not connected to the internet. If it's CORS, I want to show API is not configured properly for CORS, please inform the administrator.
How can I know whether the error is CORS or not?
I have created an interceptor and I have tried to extract data from it.
axios.interceptors.response.use((response) => response, (error) => {
if (typeof error.response === 'undefined') {
alert('A network error occurred. '
+ 'This could be a CORS issue or a dropped internet connection. '
+ 'It is not possible for us to know.')
}
return Promise.reject(error)
})

Fetch Post request not working in Custom functions Office Addin [TypeError: Network request failed]

I having been facing this error in custom functions excel Add-in, where I'm trying to call an external service inside a custom function. It works fine for a GET request such as this:
function stockPrice(ticker) {
var url = "https://api.iextrading.com/1.0/stock/" + ticker + "/price";
return fetch(url)
.then(function(response) {
return response.text();
})
.then(function(text) {
return parseFloat(text);
});
}
CustomFunctionMappings.STOCKPRICE = stockPrice;
Taken from https://learn.microsoft.com/en-us/office/dev/add-ins/excel/excel-tutorial-custom-functions#create-a-custom-function-that-requests-data-from-the-web
But gives an exception for a POST request like this:
function stockPrice(ticker) {
var url = "https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
return fetch(url, {
method: 'POST',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(body))
.then(function(response) {
return response.json();
})
.then(function(response) {
return response.somevalue;
})
.catch(e => {
console.error("Caught exception");
return JSON.stringify(e);
});
}
The above is just a sample to have an idea, of how I'm calling my service. I have tried it with 2-3 different services, and I figured out that after running fetch, the code goes to catch block, and the error value that is returned in the excel is an empty object '{}'. Since there are no ways to debug custom functions on windows, and since there is no specific error description, I'm unable to figure out the issue. I have also added my service domain to App Domain list in manifest file but still no effect.
I am not sure that particular API accepts POST requests, so you maybe running into that.
Debugging in Windows is still being worked on but you can use Excel online and F12tools to debug.
If you are on Windows, you can console.log statements in conjunction with the Runtime logging:
https://learn.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-best-practices#troubleshooting
Hope that helps and we will update this when debugging is ready on for custom functions on windows desktop.

TRANSACTION_REQUIREMENTS_CHECK not working

Since 2 weeks I trying to figure out how the Transaction Requirement Check is working.
I copy pasted exactely the same exemple you have provided in the documentation which is this one :
app.intent('verify_transaction_requirements', (conv) => {
console.log("am I entering in this intent ?");
conv.ask(new TransactionRequirements({
orderOptions: {
requestDeliveryAddress: false,
},
paymentOptions: {
googleProvidedOptions: {
prepaidCardDisallowed: false,
supportedCardNetworks: ['VISA', 'AMEX'],
// These will be provided by payment processor,
// like Stripe, Braintree, or Vantiv.
tokenizationParameters: {}
}
}
}));
});
When trying this bit of code on my mobile phone, I am receiving an error saying that my application is not responding anymore.
How error, looking at the log, my Google Function seems to send a 200 status code.
No error has been printed at all.
I have also enabled the transactions on Google Action Console.
Do you have an idea about where the problem could come from ?
Regards,
I believe the issue is because the tokenizationParameters field is empty, but it expecting some data.
Try using placeholder information in it's place, or setting up a sandbox payment processor using Stripe or Braintree:
tokenizationParameters: {
tokenizationType: 'PAYMENT_GATEWAY',
parameters: {
"gateway": 'stripe',
"stripe:publishableKey" : "pk_1234",
"stripe:version" : "1.5"
}
},

xhrPost seems to be modifying the URL resulting in either 404 or 405?

xhrPost seems to be modifying the URL resulting in either 404 or 405.
This is from a custom widget and attempting to go to a REST service on a WebSphere Liberty server.
The rest service responds correctly when using RESTClient and building the request manually.
I am using var jsonData = JSON.stringify(domForm.toObject("TaskTemplate")); so I can verify the data is correct and sending the data as that string:
data: jsonData,
the URL is hardcoded in the form and no substitution is currently being used:
<form id="TaskTemplate" name="TaskTemplate"
data-dojo-attach-point="taskTemplateNode"
method="POST"
action="http://localhost:9080/test2/rm/tasks/64/update">
I also have a GET with a URL of "http://localhost:9080/test2/rm/tasks/64/" that is working fine.
Seems to be associated with PUT or POST...
When I do the xhrPost, I am getting the following error:
"NetworkError: 404 Not Found - http://localhost:9080/test2/undefined"
since "undefined" is seen, it is like xhrPost is doing some substitution in the hardcode URL...
I am using 1.9.2-20140219-IBM version of dojo which comes with Rational Application Developer.
I have tried both xhrPost and xhrPut with the same results.
Here is the method that is invoked when the button is pushed:
applySubmit: function() {
console.log("inside applySubmit");
var jsonData = JSON.stringify(domForm.toObject("TaskTemplate"));
console.log(jsonData);
var xhrArgs = {
// url: "http://localhost:9080/test2/rm/tasks/64/update",
data: jsonData,
preventCache: true,
timeout: 10000,
handleAs: "text",
contentType: "application/json",
load: function(data) {
console.debug("applySubmit success:" + data);
},
error: function(data) {
console.debug("applySubmit error:");
}
};
console.log("doing dojo.xhrPxxx(xhrArgs);");
var deferred = dojo.xhrPost(xhrArgs); // any need to save local var and exit?
}
In the server logs, I am seeing [WARNING ] SRVE0190E: File not found: /undefined
and that is coming from the webcontainer (makes sense given the error msg above)
So, this means it is not related to my rest service, never gets to it.
This is really starting to delay our project, so any ideas about why this might be occurring would be greatly appreciated!

Restangular all("customers").getList() does not return result

I started using Restangular to send RESTful requests from my AngularJS app. I have a REST service deployed on http://localhost:20080/v1/customer which produces JSON with customer information.
When I debug AngularJS app it hits a breakpoint in the back-end REST service, however in the browser console it always logs "Failed to find customers with status code 0". Moreover, I never hit the breakpoint in the function that I register as setResponseExtractor.
I also don't see any errors in the console.
When I open http://localhost:20080/v1/customer in the browser I get the following response:
[{"customerInfo":{"name":"My Name","email":"My Email"},"id":"6ca43d0f-94a8-36e8-af3d-963584573d6d"}]
My Restangular code is as follows:
var customerModule = angular.module('customer-module',
['restangular' ]).config(
['RestangularProvider', '$httpProvider',
function (RestangularProvider, $httpProvider)
{
RestangularProvider.setBaseUrl('http://localhost\\:20080/v1');
RestangularProvider.setResponseExtractor(function (response, operation, what) {
return response;
});
...
customerModule.controller('CustomerCtrl',
[ '$scope', 'Restangular', function ($scope, Restangular)
{
var baseCustomers = Restangular.all("customer");
$scope.customers = baseCustomers.getList().then(function (result) {
console.log("Got customers", response.status);
}, function (response) {
console.log("Failed to find customers with status code", response.status);
});
Thoughts?
I'm the creator of Restangular.
You also don't have to add the responseExtractor to the config if you're just returning the response. That's what it does by default.
If you have any other problem, please contact me!
The problem turned out to be with accessing REST services running on a different port than my AngularJS app.
I am moving this thread to AngularJS mailing list - "Problems with a basic $resource.get() call"
Alec