Firebase Fetch - No Access-Control-Allow-Origin - javascript

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.

Related

Unable to access environment variables for api id and key in React App

My .env (in root dir):
REACT_APP_ID = '123456';
REACT_APP_KEY = 'abcde123';
in app.js:
useEffect(() => {
getRecipes();
}, [query]);
const getRecipes = async () => {
const response = await fetch(`https://api.edamam.com/search?q=${query}&app_id=${process.env.REACT_APP_ID}&app_key=${process.env.REACT_APP_KEY}`); //change the elements in the query to match ur ID and KEY + query
const data = await response.json();
console.log(data.hits);
setRecipes(data.hits);
}
However, it doesn't work. Error thrown in console:
Access to fetch at 'https://api.edamam.com/search?q=paneer&app_id=***;&app_key=***;' 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.
Failed to load resource: net::ERR_FAILED
I've tried restarted the server by npm start but it doesn't work.
How to fix this?
The problem is not related to ReactJS here. The issue you are facing is about the CORS policy which is related to the networks and headers of the response. you should have something like this in your request header:
Access-Control-Allow-Origin: http://127.0.0.1:3000
Also try to use fetch with credentials included, something like this:
fetch(https://api.edamam.com/search?q=${query}&app_id=${process.env.REACT_APP_ID}&app_key=${process.env.REACT_APP_KEY}`, {
credentials: 'include'
});

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.

using Riot games API with JS and fail to load response data

I have tried to use Riot games API, the below code has returned 'Status Code: 200'and seems like ok and then I got two errors as below.
Access to fetch at 'https://oc1.api.riotgames.com/lol/summoner/v4/summoners/by-name/edisona?api_key=RGAPI-xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' from origin 'http://127.0.0.1:5500' 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.
GET https://oc1.api.riotgames.com/lol/summoner/v4/summoners/by-name/edisona?api_key=RGAPI-xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx net::ERR_FAILED
So I added { mode: 'no-cors' } and error is gone, but there is no data that has been returned in the console after that I just use the URL directly and the browser shows the right data. I do not know why it happened, I appreciate if you can help me.
const name = 'edisona';
const api_key = 'RGAPI-xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
const url =
'https://oc1.api.riotgames.com/lol/summoner/v4/summoners/by-name/' +
name +
'?api_key=' +
api_key;
fetch(url)
.then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
This seems like a Cross-Orgin request error (you didn't add CORS headers to the proxied request).
Try using CORS-Anywhere, a NodeJS reverse proxy to do just that.
Here's a demo. Try reading some about CORS: https://fetch.spec.whatwg.org/#cors-protocol-and-credentials

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.

Retrieve LinkedIn access token

I'm trying to get linkedIn oauth2 access token but I stuck on making last request to https://www.linkedin.com/oauth/v2/accessToken
const body = new URLSearchParams([
['grant_type', 'authorization_code'],
['code', code],
['redirect_uri', 'http://localhost:3000/'],
['client_id', CLIENT_ID],
['client_secret', CLIENT_SECRET]
]);
const headers = new Headers({'Content-Type': 'x-www-form-urlencoded'});
window.fetch('https://www.linkedin.com/oauth/v2/accessToken', method: 'POST',body, headers)
.then(response => response.json())
.then(data => {
// rest of code
})
LinkedIn returns
Fetch API cannot load https: //www.linkedin.com/oauth/v2/accessToken. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: //localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
so I tried to make request in 'no-cors' mode. I've got 200 but I can't get body of response,status is 0, body is null and response.json() throws SyntaxError: Unexpected end of input.
For anyone who came across this problem. We solved it by passing data from LinkedIn (code) to our backend. Backend have no need to send any preflight OPTIONS requests and can get access token without problem.
I found out your issue,
The Content-Type header value is not correct.
It's meant to be
const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
NOT
const headers = new Headers({'Content-Type': 'x-www-form-urlencoded'});
DOCS: https://developer.linkedin.com/docs/oauth2 (Step 3)

Categories

Resources