Cannot fetch data from Wikipedia API - javascript

let dataObj = [];
const query = 'marvel';
fetch(`https://en.wikipedia.org/w/api.php?action=query&titles=${query}&prop=revisions&rvprop=content&format=json&formatversion=2`)
.then(data => data.json())
.then(data => dataObj.push(data))
.catch(err => console.log(err));
This is the error that I receive:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s.codepen.io' 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 set the mode to no-cors but still no luck.

Try adding the query parameter origin=* to help resolve the CORS issue:
https://en.wikipedia.org/w/api.php?action=query&titles=${query}&prop=revisions&rvprop=content&format=json&formatversion=2&origin=*
Hopefully that helps!

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 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

Why I get the error below while fetching a feed?

Failed to load https://feeds.bbci.co.uk/news/rss.xml: 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
My code looks like this:
fetch("https://feeds.bbci.co.uk/news/rss.xml")
.then(res => res.json())
.then(res => console.log(res))
I tried almost everything. Set headers, set modes, but nothing works. What is the problem?
You are not allowed to do this, because the BBC website did not set the right CORS headers.
Only when the right CORS headers are set, you can make requests from other domains. Your best option is to do this via a server-side proxy, or get a job at BBC and try to add the right headers.
You can try to use RSS2json instead:
google.load("feeds", "1");
google.setOnLoadCallback(() => {
const url = 'https://feeds.bbci.co.uk/news/rss.xml';
new google.feeds.Feed(url).load(function(result) {
!result.error && console.log(result.feed.entries);
});
});
<script type="text/javascript" src="https://rss2json.com/gfapi.js"></script>

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)

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