Error: timeout of 1000ms exceeded (cannot connect with axios) - vue.js

I'm getting that problem while I'm trying to connect my frontend with backend, so I did this and installed axios:
let Service = axios.create({
baseURL: 'http://localhost:3000/',
timeout: 1000
})
And when I try to send the data to backend I'm still getting this kind of error:
createError.js?2d83:16 Uncaught (in promise) Error: timeout of 1000ms exceeded
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleTimeout (xhr.js?b50d:96)
Backend is working properly when I run it. So I don't understand what could it be?

Related

Why am I getting 3 "Cross-Origin Request Blocked" messages

I have a Svelte application and I am trying to render data from the API but I keep on getting 3 error messages.
The code works properly on node but not on Svelte.
Below is the Svelte code:
<script lang="ts">
import { onMount } from "svelte";
let word = [];
onMount(async () => {
const response = await fetch(
"https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5",
{
method: "GET",
headers: {
"X-RapidAPI-Key": "KEY",
"X-RapidAPI-Host": "random-words5.p.rapidapi.com",
},
}
);
word = await response.json();
console.log(word);
});
</script>
<p>{word}</p>
And below are the error messages:
ross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://localhost:5173’).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS request did not succeed). Status code: (null).
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
How do I get my code to render out the data from the API in Svelte?
The CORS issue occurs when you try to fetch a resource from a local environment, this is the case when you run your app in dev mode.
I use the CORS Unblock extension to fix the issue, give it a try.

Expo app is throwing when locally hosted api is called

I am using expo in my project and I hosted a local server for API. When I try connecting the API with the expo project it gives me network error:
error Error: Network Error
at createError (F:\Projects\react-native-food-app\node_modules\axios\lib\core\createError.js:16:15)
at XMLHttpRequest.handleError (F:\Projects\react-native-food-app\node_modules\axios\lib\adapters\xhr.js:117:14)
at XMLHttpRequest.dispatchEvent (F:\Projects\react-native-food-app\node_modules\event-target-shim\dist\event-target-shim.js:818:35)
at XMLHttpRequest.setReadyState (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:609:16)
at XMLHttpRequest.__didCompleteResponse (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:396:12)
at F:\Projects\react-native-food-app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:517:9
at RCTDeviceEventEmitter.emit (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\vendor\emitter\_EventEmitter.js:135:33)
at MessageQueue.__callFunction (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:27)
at F:\Projects\react-native-food-app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:12
at MessageQueue.__guard (F:\Projects\react-native-food-app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:9)
This is the code for API calling
const instance = axios.create({
baseURL: "http://127.0.0.1:8000/api/",
});
It works just fine in insomnia but throws an error when I call the API in expo
expo is not support localhost server.
you must use the ip instead of localhost
ipconfig #window
networksetup -getinfo Wi-Fi #mac
and then
const instance = axios.create({
baseURL: "http://192.168.0.100:8000/api/",
});

Can't fetch data from local api React-Native

I have a web application, in react using an API made in Laravel. I want to make a mobile app using the same API. I can't fetch data, because I get NETWORK REQUEST FAILED error. This is how I try to fetch data:
handleButton = () => {
try {
fetch(`127.0.0.1:8081/test`).then(response =>
console.log(response)
);
} catch (e) {
console.log(e);
}
};
I tried changing the ip in dev settings to my machine id, i tried using localhost not the ip(127.0.0.1) but none of those fixed it... I can't seem to find anything else. Here is the error text:
Possible Unhandled Promise Rejection (id: 0):
TypeError: Network request failed
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:42556:18)
at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:47998:27)
at XMLHttpRequest.setReadyState (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:46859:20)
at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:46686:16)
at blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:46796:47
at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16875:37)
at MessageQueue.__callFunction (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16488:44)
at blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16245:17
at MessageQueue.__guard (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16442:13)
at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/cfc373de-8318-4df3-b46a-7b17d4926c5e:16244:14)
EDIT:
I am using android studio's emulator, because i don't have an android device running android > 5
Use the IP of your machine on the local network.
Open up terminal/cmd.
If you're using a mac, you can use ifconfig and it's usually under en0. You will see something like 192.168.0.32 or similar.
If you're using windows, you can use ipconfig.

webpack dev-server: Avoid proxy errors on HTTP errors returned from proxy target

I have a Vue.js project where I have configured a webpack dev-server to proxy all requests to the UI to my backend server. Here is the relevant part of vue.config.js:
devServer: {
contentBase: PATHS.build,
port: 9000,
https: false,
hot: true,
progress: true,
inline: true,
watchContentBase: true,
proxy: {
'^/': {
target: 'http://127.0.0.1:8089',
secure: false
},
}
},
I've noticed that if the HTTP response code from http://127.0.0.1:8089 is anything other than 2xx then the proxy fails with the following error:
Proxy error: Could not proxy request /api/test from localhost:9000 to http://127.0.0.1:8089.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (HPE_INVALID_CHUNK_SIZE).
This also causes the HTTP response code from the request to localhost:9000 to be 500 for any error and all the information about what went wrong on the server side is lost. This is problematic as I want to be able to extract information from error responses to display to the user.
I know it's possible to do because I had it working on an older Angular project which I think was using Webpack 3 (am now using Webpack 4). I tried copying all the dev-server config from this project but it just doesn't seem to work here!
EDIT: I was wrong. The Proxy error does not occur on every bad response but only for one of the requests which is a multipart file upload. Still unable to reproduce this in a smaller example to put on github though so struggling to pinpoint the cause.
This error message comes from node_modules/#vue/cli-service/lib/util/prepareProxy.js, which define a onError callback for node-http-proxy;
So I did some experiment, make back-end api generate 400 404 500 response, but I didn't got this error.
After I happen to close back-end api, error arise:
Proxy error: Could not proxy request /hello from localhost:8080 to http://localhost:8081 (ECONNREFUSED).
I search in the doc and find these:
The error event is emitted if the request to the target fail. We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them
So the onError do not handle error code, is called only when request fail (500 response is still treated as a complete request, connection refuse is not)
Go back to your error message, [HPE_INVALID_CHUNK_SIZE] means bad request to the back-end api. In this issue, it gives an solution: add a keep-alive header:
devServer: {
publicPath: 'http://localhost:9090/front/static-dev/build/',
port: 9090,
proxy: {
'/**': {
target: 'http://localhost:8080',
secure: false,
changeOrigin: true,
headers: {
Connection: 'keep-alive'
}
},
open: true
}
I have finally found the problem, and I apologise, it was a lot more of a specific issue than I originally thought when I wrote the question.
Issue was to do with a request which was proxied to another server using the Spring RestTemplate:
e.g.
#PostMapping("/upload")
public ResponseEntity upload(#RequestParam("file") MultipartFile file)
throws Exception {
String baseUrl = serviceProperties.getAddress();
HttpEntity<MultiValueMap<String, Object>> request = createMultipartRequest(file.getBytes());
return restTemplate.postForEntity(baseUrl + "/api/upload", filterRequest, String.class);
}
The ResponseEntity returning from the rest template proxy contained the header "Connection: close" when the response was anything other than 200 which cause the connection to close and caused this request to fail to return anything which subsequently made the dev-server proxy fail on the UI.
Fixed this by not passing the response headers from the rest template proxy to the response:
#PostMapping("/upload")
public ResponseEntity upload(#RequestParam("file") MultipartFile file)
throws Exception {
String baseUrl = serviceProperties.getAddress();
HttpEntity<MultiValueMap<String, Object>> request = createMultipartRequest(file.getBytes());
ResponseEntity response = restTemplate.postForEntity(baseUrl + "/api/upload", filterRequest, String.class);
return new ResponseEntity<>(response.getBody(), response.getStatusCode());
}

jQuery .ajax call returning error when accessing Java Spring service via domain name based URL

My application's HTML5, jQuery Mobile frontend talks to Java server (Spring, Hibernate, MySQL). The application works fine on my notebook as well as in QA environment. On QA, I'm accessing the application using the server's IP address.
When I host the application in Live environment (the same server as QA but a different web app in Tomcat) and try to access it using URL with the domain name, $.ajax calls in the application return error.
One of the calls is as follows:
$.ajax({
type : "GET",
url : "http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi/rest/resource/getResourceTypes",
cache : false,
async : false,
dataType : 'json',
success : function(rTypes) {
Alert("success!");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown);
}
});
I get the following error in Firefox:
An error has occurred making the request: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://www.smartcloudlearning.mobi/js/jquery-1.7.1.min.js :: <TOP_LEVEL> :: line 4" data: no]
I get the following error in Chrome:
An error has occurred making the request: Error: NETWORK_ERR: XMLHttpRequest: Exception 101
In the server log, I see that the requested Spring service was successfully invoked but it looks like the client doesn't receive the data!
If I hit the URL
http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi/rest/resource/getResourceTypes
directly in the browser, I get expected results! I sense that this is somehow due to how I forward server request from Apache to Tomcat.
The following are the lines in Apache / httpd server's httpd.conf file:
ProxyPass /SmartCloudLearningMobi http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi
ProxyPassReverse /SmartCloudLearningMobi http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi
Can anyone tell me what's amiss here? Much appreciated!
I managed to solve the problem:
The browser was giving the error on .ajax call because I had port number in my URL. The port number got carried over when I created 'live' URL from my QA URL. When I removed the port number from the .ajax call's URL, the call started returning success!
Jason Foglia, your statement "... and also the port..." nudged me to explore that angle... thanks a lot!
You're probably getting an error because of a security concept called "same origin policy" which doesn't allow you to call a service from a different domain. Or at least, disallow you from calling a method in that service.
Same discussion is found here - AJAX Cross Domain
You can however implement a cross-domain using JSONP - Wikipedia on JSONP
The solution is to change the datatype to JSONP:
$.ajax({
url:"http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi...",
dataType: 'jsonp',
...
});
Try using an relative url:
If that doesn't work is the domain name the same as the url and also the port.
Browsers don't allow cross domains.
$.ajax({
type : "GET",
url : "/SmartCloudLearningMobi/rest/resource/getResourceTypes",
cache : false,
async : false,
contentType : "application/json"
dataType : 'json',
success : function(rTypes) {
Alert("success!);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown);
}
});
The browser was giving the error on .ajax call because I had port number in my URL. The port number got carried over when I created 'live' URL from my QA URL. When I removed the port number from the .ajax call's URL, the call started returning success!
Jason Foglia, your statement "... and also the port..." nudged me to explore that angle... thanks a lot!