Local HTTP Request not sending with Axios on React Native Expo app - reactjs

I am writing a react native expo app that utilizes a .NET backend that I've already established and has worked quite well for a while. Recently, I've gotten to the point of attempting local http requests with axios for my mobile app rather than mock data, and it worked wonderfully for a bit. I have a few get requests that are called in a useEffect like this:
useEffect(() => {
async function getAll() {
const response = await axios({
method: 'GET',
url: `${baseUrl}/ItemName`,
headers: {
authorization: `Bearer ${authToken}`,
'content-type': 'application/x-www-form-urlencoded'
}
}).catch(err => console.log(err));
if(response?.data) {
setItemName(response.data);
}
}
getAll();
}, []);
Then after that was working, I wanted to put in authentication within the app itself rather than using the backend Swagger and copying the token every 30 minutes. Made a signup page and the form worked just fine, but when I made the new axios post request, none of the requests worked - even those that were working before hand. The post looks like this:
const postNewUser = async (values) => {
try {
const postObject = {
method: 'POST',
url: `${baseUrl}/User/Register`,
data: {
firstName: values.firstName,
lastName: values.lastName,
username: values.username,
password: values.password,
email: values.email,
phoneNumber: values.phone,
birthDate: moment(values.birthDate).toISOString()
},
headers: {
'content-type': 'application/json'
}
};
const response = await axios(postObject);
if(response) {
navigation.navigate('Login', {
desiredUsername: values.username
});
}
} catch(err) {
console.log('Error: ', err);
}
}
I've been googling for over a week now trying different answers multiple different times. I've tried updating my nodejs, tried different versions of axios, tried different baseUrls for the request (localhost, 10.0.2.2, and my personal IP) but none of them work. Strangely, localhost and my IP both return very quickly, and 10.0.2.2 takes a solid 30 seconds but returns the same error message.
I have put a log into the user controller on my backend to show whether or not I'm actually hitting the backend or not, and with postman or swagger I get there just fine. With the mobile axios call I don't hit that log, so I'm not even getting to the backend at all. Instead I'm getting a not-so-useful error as follows:
Stack: AxiosError#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:114554:29
handleTimeout#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:115572:39
dispatchEvent#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:30065:31
setReadyState#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:28693:33
__didCompleteResponse#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:28499:29
emit#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:2310:40
__callFunction#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:21321:36
#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:21071:31
__guard#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:21269:15
callFunctionReturnFlushedQueue#http://personalIP:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false:21070:21
callFunctionReturnFlushedQueue#[native code]
Message: timeout exceeded
Name: AxiosError
Code: ECONNABORTED
Config: {
"adapter": [
"xhr",
"http"
],
"data": "{\"firstName\":\"Test\",\"lastName\":\"Test\",\"username\":\"test\",\"password\":\"P#ssw0rd\",\"email\":\"email#example.com\",\"phoneNumber\":\"5555555555\",\"birthDate\":\"2022-11-27T19:13:57.458Z\"}",
"env": {
"Blob": [Function Blob
],
"FormData": [Function FormData
]
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"maxBodyLength": -1,
"maxContentLength": -1,
"method": "post",
"timeout": 0,
"transformRequest": [
[Function transformRequest
]
],
"transformResponse": [
[Function transformResponse
]
],
"transitional": {
"clarifyTimeoutError": false,
"forcedJSONParsing": true,
"silentJSONParsing": true
},
"url": "http://10.0.2.2:5000/api/User/Register",
"validateStatus": [Function validateStatus
],
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN"
}
Request: {
"DONE": 4,
"HEADERS_RECEIVED": 2,
"LOADING": 3,
"OPENED": 1,
"UNSENT": 0,
"_aborted": false,
"_cachedResponse": undefined,
"_hasError": true,
"_headers": {
"accept": "application/json, text/plain, */*",
"content-type": "application/json"
},
"_incrementalEvents": false,
"_lowerCaseResponseHeaders": {},
"_method": "POST",
"_perfKey": "network_XMLHttpRequest_http://10.0.2.2:5000/api/User/Register",
"_performanceLogger": {
"_closed": false,
"_extras": {},
"_pointExtras": {},
"_points": {
"initializeCore_end": 606677771.370125,
"initializeCore_start": 606677745.343875
},
"_timespans": {
"network_XMLHttpRequest_http://10.0.2.2:5000/api/User/Register": [Object
],
"network_XMLHttpRequest_http://personalIp:19000/logs": [Object
],
"network_XMLHttpRequest_http://personalIp:19000/symbolicate": [Object
],
"network_XMLHttpRequest_http://personalIp:5000/api/User/Register": [Object
],
"network_XMLHttpRequest_http://localhost:5000/api/User/Register": [Object
]
}
},
"_requestId": null,
"_response": "The request timed out.",
"_responseType": "",
"_sent": true,
"_subscriptions": [],
"_timedOut": true,
"_trackingName": "unknown",
"_url": "http://10.0.2.2:5000/api/User/Register",
"readyState": 4,
"responseHeaders": undefined,
"status": 0,
"timeout": 0,
"upload": {},
"withCredentials": true
}
I'm testing this currently on my mobile expo app. I've tested in the past on the web version but SecureStore doesn't work with web. I was able to confirm before adding the new requests that the mobile version was able to call the getAll just fine before the signup was added.

Related

Alexa smart home skill lambda is throwing a LWA error

I am developing alexa smart home skill. As part account linking i am getting AcceptGrant. I am getting below error,When i am getting access_token and refresh_token by using authorization code which i get as part of AcceptGrant request. Something i was missed. Same code is working for another skill. Could you please tell me what i missed?
ERROR Invoke Error {
"message": "Request failed with status code 400",
"name": "Error",
"stack": "Error: Request failed with status code 400\n at createError (/var/task/node_modules/axios/lib/core/createError.js:16:15)\n at settle (/var/task/node_modules/axios/lib/core/settle.js:17:12)\n at IncomingMessage.handleStreamEnd (/var/task/node_modules/axios/lib/adapters/http.js:293:11)\n at IncomingMessage.emit (events.js:412:35)\n at endReadableNT (internal/streams/readable.js:1334:12)\n at processTicksAndRejections (internal/process/task_queues.js:82:21)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 1000,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"User-Agent": "axios/0.24.0",
"Content-Length": 206
},
"method": "post",
"url": "https://api.amazon.com/auth/o2/token",
"data": "grant_type=authorization_code&code=RHmcOGELgCJeAHZUDtJm&client_id=amzn1.application-oa2-client.2e90a623fe5343baa8d201d038dd8666&client_secret=47cc11f1a945dde6d9844cf33ff2962fe064703c5a2ad5d651dbc29af31b539d"
},
"status": 400
}
Code
getTokensWithAuthCode(authCode) {
const body = querystring.stringify({
grant_type: 'authorization_code',
code: authCode,
client_id: ALEXA_CLIENT_ID,
client_secret: ALEXA_CLIENT_SECRET
});
return this.amazonTokenPost(body);
},
amazonTokenPost(body) {
return axios.post('https://api.amazon.com/auth/o2/token', body, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
timeout: 1000
});
}

Can't read response data and headers in an AngularJS interceptor

I have an API in my server that sends a custom header (lets name it "customHeader") that responds to http://localhost:8081/my/test/api.
I'm trying to read that custom response header from an interceptor in angularJS:
angular.module('oauth.interceptor', []).factory('readResponseHeader', ['$q',
function ($q) {
return {
response': function(response) {
console.log("response: %o", JSON.stringify(response));
console.log("headers: %o", response.headers());
return response;
}
}
}
]);
But all I get are empty data and headers in response. The console log shows the following json as response:
{
"data": [],
"status": 200,
"config": {
"method": "POST",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "http://localhost:8081/my/test/api",
"data": {
"example": "request data"
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Bearer XXXXXXXXX..."
},
"cached": false
},
"statusText": "OK"
}
And the following as headers:
{
"content-type": "application/json; charset=UTF-8"
}
I expected my customHeader to be there, and be able to read it with something like:
response.headers().customHeader
But it clearly isn't there (in fact, many other headers are missing!).
How am I supposed to read it?
I finally found the problem wasn't really in the AngularJS part, but on the server side part.
The point is that, to be able to access the header, the server must add the Access-Control-Expose-Headers header containing the name of the custom header, something like this:
Access-Control-Expose-Headers: customHeader

Axios GET request timeouts randomly

We are working on a React app, which makes REST API calls using Axios. And we are randomly seeing request timeouts. We checked the network connection and it was fine (100 MBPS connection). We checked our server logs, the request reached the server and it got processed without any errors. But the client never got back the response. I am adding the code we use to make those api calls below. If you find any issue with the code, a solution will be much appreciated. If you think that the code is looking good, then please give us some tips on resolving/debugging the timeout. I am also adding the error below.
import axios from 'axios';
import axiosRetry from 'axios-retry';
import { v4 } from 'uuid';
axios.defaults.timeout = 30000;
axios.interceptors.request.use((config) => {
const updatedConfig = { ...config };
updatedConfig.headers['X-CORRELATION-ID'] = v4();
return updatedConfig;
});
axiosRetry(axios, {
retries: 3,
retryDelay: (retryCount) => retryCount * 1000,
});
axios({
method: 'get',
url: `${requestURL}`,
headers: {
authorization: `Bearer ${token}`,
},
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
{
"error": {
"message": "timeout of 30000ms exceeded",
"name": "Error",
"stack": "Error: timeout of 30000ms exceeded\n at e.exports (https://file.js:2:2141051)\n at XMLHttpRequest.h.ontimeout (https://file.js:2:2140157)",
"config": {
"url": "requestURL",
"method": "get",
"headers": {
"Accept": "application/json, text/plain, */*",
"authorization": "Bearer TOKEN",
"X-CORRELATION-ID": "UDID"
},
"transformRequest": [null],
"transformResponse": [null],
"timeout": 30000,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"axios-retry": {
"retryCount": 0,
"lastRequestTime": 1597096169071
}
},
"code": "ECONNABORTED"
}
}
Thanks in advance

How to pass body in post request fetch api call in React Native

My url if opened on browser gives the following error:(attached image)
Body of my api call looks like below :
{
"entityId": 4071,
"listViewId": 0,
"asLookup": false,
"retrieveAllFields": true,
"fullTextSearch": "",
"query": [
],
"pagination": {
"pageNumber": 0,
"recordsCountPerPage": 0
},
"sorting": {
"fieldId": 0,
"direction": 0
}
}
I am calling api in react native using fetch below :
try {
let response = await fetch('url', {
method: 'POST',
headers: {
'tenantid': '1',
'Content-Type': 'application/json',
'language': '0',
},
body: JSON.stringify({
entityId: 4071,
listViewId: 0,
asLookup: false,
retrieveAllFields: true,
fullTextSearch: "",
query: [
],
pagination: {
pageNumber: 0,
recordsCountPerPage: 0
},
sorting: {
fieldId: 0,
direction: 0
}
})
})
let json = await response.json();
console.log("This is response" + json)
this.setState({records: json.results, isFetching:false});
}catch(error){
this.setState({errorMessage:error})
console.log("This is error"+error)
}
This gives me response : Network failed request. Also tried with the inverted commas, still same response. I am newbie in react native but I have made api calls in the past but this one wouldnt work. If anyone can look into this, would be of great help!
did you use the correct url ?
it should looks like something like this
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue'})
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
});
maybe you should look on the documentations
https://reactnative.dev/docs/network

React js Axios call

I'm fairly to new to React and I can't seem to be able to successfully make a call to an external API using Axios.
The guidelines of the external API are:
Request (in case we know all the parameters)
{
"service": "login",
"username": "john",
"password":"aitis",
"appId": "2001",
"COMPANY": "1000",
"BRANCH": "1000",
"MODULE": "0",
"REFID": "1",
---- optional ---
"LOGINDATE": "2017-12-31 13:59:59",
"TIMEZONEOFFSET": -120
}
Response
{
"success": true,
"clientID": "Wj8Te8EqWghDM......... .....wYGtzlyc1At%2bPrG8t"
}
My code is:
componentDidMount() {
axios.get('http://...serverurl....', {
params: {
service: 'login',
username: 'john',
password: 'aitis',
appID: '2001',
company: '1000',
branch: '1000',
module: '0',
refid: '1'
},
headers: {
'accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS'
}
})
.then(response => console.log(response));
}
Instead of getting the clientID response I get this:
Response
{data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
data:
success: false
errorcode: 0
error: "JSON Object must begin with "{" at character 2 of service=login&username=john&password=aitis&appID=2001&Company=1000&Branch=1000&Module=0&Refid=1 JSON Syntax Error : at charact↵
error on character : 2"
__proto__: Object
status: 200
statusText: ""
...
Is something wrong with my call?
Thanks in advance.
If want to send a GET request with those params set those in URL
const URL = `${baseURL}/url?service=login&username=jhon&password=aitis&appID=2001&company=1000&branch=1000&module=0&refid=1`;
axios.get(URL).then(response => console.log(response));
I figured it out. I had to use axios.post instead of axios.get.
Thank you all very much

Resources