Capturing full fetch errors [duplicate] - javascript

This question already has answers here:
Catching an Access-Control-Allow-Origin error in JavaScript
(2 answers)
Closed 3 years ago.
I have a fetch request:
fetch(url, {
}.then(function(resp))
// do something
}.catch(err => {
console.log(err);
}
My question involves grabbing the entire stack trace of err. For example, here is the real error message:
Access to fetch at 'https://www.google.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Great. This is a usable message. However, console.log(err) prints out TypeError: Failed to fetch. That's a really useless error message. Is there any way to capture that entire entire message that was logged in console (ie. var message = //the full error? err.stack does not seem to be a function and err.message returns the same useless Failed to fetch message

In general, when using fetch, you want to make use of the response.ok attribute, which is a bit confusing at first. This is a really good article on it, and it contains this example which is more or less what you want to do:
fetch("http://httpstat.us/500")
.then(function(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}).then(function(response) {
console.log("ok");
}).catch(function(error) {
console.log(error);
});
That said, you'll still get TypeError: Failed to fetch if you end up with a CORS error because they don't give you a nice error code (e.g. 404), they just cancel the HTTP request

Related

I have an error with my API fetching, what does it mean [duplicate]

This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 1 year ago.
I was trying to retrieve data from an API and it worked for several days but now, it gives this error:
[Error] Preflight response is not successful
[Error] Fetch API cannot load https://imdb-api.com/en/API/Search/my_key/m due to access control checks.
[Error] Failed to load resource: Preflight response is not successful (m, line 0)
What does this mean?
By the way, here's the code(relatively simple):
export async function getAPI(url, settings, callback) {
try {
const response = await fetch(url, settings)
var result = await response.json()
callback(result)
} catch {
callback({errorMessage: "This is an error message"})
}
}
Does it have something to do with the code or something else?
Thanks a lot in advance :)
I'm thinking this is either a CORS issue or perhaps has something to do with your header

Using fetch() to get data from API [duplicate]

This question already has answers here:
Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'
(5 answers)
Closed 4 years ago.
When trying to resolve a fetch promise with JS is set the mode to 'no-cors' based on this answer. However setting the mode to 'cors' results in having:
Access to fetch at
'{endpoint}'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
So I wrote this in my function:
search() {
return fetch(`${baselink}${summonerEndpoint}${summoner}${apikey}`, {mode: 'no-cors'}).then(response => {
return response.json()
}).then(jsonResponse => {
console.log(jsonResponse);
if (!jsonResponse.info) {
return [];
}
return jsonResponse.info.items.map(info => ({
id: info.id,
accountId: info.accountId,
name: info.name,
profileIconId: info.profileIconId,
revisionDate: info.revisionDate,
summonerLevel: info.summonerLevel
}));
});
}
This results in following error Uncaught (in promise) SyntaxError: Unexpected end of input for return response.json(), but with no further message. What am I doing wrong?
If an opaque response serves your needs
It doesn't. You want to see the response. You can't see an opaque response (that is what opaque response means).
no-cors mode means that if the browser has to do anything that requires permission from CORS, it will fail silently instead of throwing an error.
So it is silently failing to get the response, then trying to parse that nothing as JSON (which throws a different error).
You need:
To not use no-cors mode
The server to grant permission using CORS
See this question for more information about CORS in general.

How can I get the complete error from a failed fetch request? [duplicate]

This question already has answers here:
Catching an Access-Control-Allow-Origin error in JavaScript
(2 answers)
Closed 2 years ago.
I want to catch complete errors from fetch, e.g. I want the red marked stuff as string:
However, in my catch block I only get "Failed to fetch". This is my code:
try {
response = await fetch(url, {
method: method,
body: JSON.stringify(payload),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`RESPONSE NOT OK: ${response.status}`);
}
console.info('got 200 json response:' + (await response?.json()));
} catch (e) {
console.error('CATCH BLOCK:' + e.message); // only gives me "Failed to fetch"
}
So, how can I get the complete fetch error in a string to e.g. show it directly in my webinterface?
Update
Just to clarify this: I know how to fix the error itself. This question is only about how to get the complete error as string.
There are actually two requests, not one, hence the confusion. Preflight requests are issued automatically by your browser and are completely transparent to your code. They're logged to the console only to help the developer see the problem. Outside of that, your fetch request doesn't have any information about them.
You can read about it in depth in this question.
While it won't give you information about the initial failed request, if you want, you have the option to fire off a preflight request yourself by making an OPTIONS request:
OPTIONS /resource/foo
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: origin, x-requested-with
Origin: https://foo.bar.org

Posting form data to App Script not working [duplicate]

This question already has answers here:
Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'
(5 answers)
Closed 4 years ago.
When trying to resolve a fetch promise with JS is set the mode to 'no-cors' based on this answer. However setting the mode to 'cors' results in having:
Access to fetch at
'{endpoint}'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
So I wrote this in my function:
search() {
return fetch(`${baselink}${summonerEndpoint}${summoner}${apikey}`, {mode: 'no-cors'}).then(response => {
return response.json()
}).then(jsonResponse => {
console.log(jsonResponse);
if (!jsonResponse.info) {
return [];
}
return jsonResponse.info.items.map(info => ({
id: info.id,
accountId: info.accountId,
name: info.name,
profileIconId: info.profileIconId,
revisionDate: info.revisionDate,
summonerLevel: info.summonerLevel
}));
});
}
This results in following error Uncaught (in promise) SyntaxError: Unexpected end of input for return response.json(), but with no further message. What am I doing wrong?
If an opaque response serves your needs
It doesn't. You want to see the response. You can't see an opaque response (that is what opaque response means).
no-cors mode means that if the browser has to do anything that requires permission from CORS, it will fail silently instead of throwing an error.
So it is silently failing to get the response, then trying to parse that nothing as JSON (which throws a different error).
You need:
To not use no-cors mode
The server to grant permission using CORS
See this question for more information about CORS in general.

Firebase Fetch - No Access-Control-Allow-Origin

I'm developing an app with React + Redux and I have my JSON database within a Firebase DB.
To do this I'm tryin to fetch my data from a valid URL (validated from Firebase simulator)
let firebase = 'https://******.firebaseio.com/**/*/***/*'
return (dispatch) => {
return fetch(firebase)
.then(res => res.json())
.then(json => dispatch({ type: 'GET_JSON', payload: json }))
}
This returns to me the error:
Fetch API cannot load https://console.firebase.google.com/project/****/database/data/**/*/***/*. Redirect from 'https://console.firebase.google.com/project//database/data/**///' to 'https://accounts.google.com/ServiceLogin?ltmpl=firebase&osid=1&passive=true…ole.firebase.google.com/project//database/data///**/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.`
I've tried many solutions, like adding to fetch's second argument { mode: 'no-cors', credentials: 'same-origin'}, but when I try this i get Uncaught (in promise) SyntaxError: Unexpected end of input.
What am I missing?
likely error that arise to cors blocked when using firebase is
when you initiate a put or get request with an incomplete firebase url
e.g
// wrong form
this.http.get('https://******.firebaseio.com/data') //this will throw an exception
// correct form
this.http.get('https://******.firebaseio.com/data.json')
I had this problem with a serviceworker implementation of fetch
self.addEventListener('fetch', (e) => {
fetch(e.request) // valid arg && works with firebase
fetch(e.request.url) // valid arg but will cause access-control error!
}
For a simple request to be allowed cross-domain, the server simply needs to add the Access-Control-Allow-Origin header to the response.
Also refer this turorial, if you have any doubts
Cross-Origin XMLHttpRequest
Using CORS.

Categories

Resources