0

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)  
});
Daniel Wang
  • 57
  • 1
  • 5

1 Answers1

0

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

benhatsor
  • 1,863
  • 6
  • 20
  • thanks for your suggestion, i am using CORS-Anywhere and add a scripts for proxy with `var host = process.env.HOST || '0.0.0.0'; var port = process.env.PORT || 8080; var cors_proxy = require('cors-anywhere'); cors_proxy.createServer({ originWhitelist: [], // Allow all origins requireHeader: ['origin', 'x-requested-with'], removeHeaders: ['cookie', 'cookie2'] }).listen(port, host, function() { console.log('Running CORS Anywhere on ' + host + ':' + port); }); ` – Daniel Wang Nov 20 '20 at 09:51
  • also, I create `const proxy='http://127.0.0.1:8080/'` and` fetch(proxy+url)` so it is working now, but the port has to use 8080, – Daniel Wang Nov 20 '20 at 09:52