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
Related
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.
I am trying to post comment on the YouTube video using the YouTube API using ReactJS. But instead of using the gapi for signInWithGoogle, I am using firebase and the access_token returned by firebase.
My code looks something like this.
const url = `https://youtube.googleapis.com/youtube/v3/commentThreads?key=${MY_API_KEY}&part=snippet`
const requestOptions = {
method: "POST",
headers: {
Authorization: `Bearer ${ACCESS_TOKEN}`,
'Content-Type': 'application/json',
Accept: 'application/json'
}
body: JSON.stringify({
"snippet": {
"videoId": "[SOME_VIDEO_ID]",
"topLevelComment": {
"snippet": {
"textDisplay": "test",
}
}
}
})
}
fetch(url, requestOptions)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))
But it throws error saying that
{
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Invalid Credentials",
"domain": "global",
"reason": "authError",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED"
}
}
What is the problem here?
Instead of using firebase I used a npm package called react-google-login, which provides the access_token. I used that access token to authorize the YouTube API, which worked.
https://www.npmjs.com/package/react-google-login
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
});
}
Post request works but response (on code 200) is not returned.
`axios
.post(url, JSON.stringify(data))
.then((resp) => {
console.log("resp: ", resp.data.body);
console.log("result: ", resp.data.result);
alert(Success ${JSON.stringify(resp.data.result)});
})
.catch((err) => {console.error("Problem with Add: ", err); }); };`
When running the same request in postman i get the response with custom error:
`{
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "",
"Access-Control-Allow-Origin": "",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Credentials": true
},
"body": ""Success"",
"result": [
{
"#full_error": "ERROR 1062 (23000): Duplicate entry '501151' for key 'PRIMARY'"
}]}`
Please advise
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