#javascript #riot-games-api
#javascript #riot-games-api
Вопрос:
Я попытался использовать Riot games API, приведенный ниже код вернул «Код состояния: 200» и кажется, что все в порядке, а затем я получил две ошибки, как показано ниже.
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
Итак, я добавил { mode: 'no-cors' }
и ошибка исчезла, но в консоли нет данных, которые были возвращены после этого, я просто использую URL напрямую, и браузер показывает правильные данные. Я не знаю, почему это произошло, я ценю, если вы можете мне помочь.
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)
});
Ответ №1:
Это похоже на ошибку перекрестного запроса (вы не добавили заголовки CORS к прокси-запросу).
Попробуйте использовать CORS-Anywhere, обратный прокси-сервер NodeJS, чтобы сделать именно это.
Вот демонстрация. Попробуйте прочитать что-нибудь о CORS: https://fetch.spec.whatwg.org/#cors-protocol-and-credentials
Комментарии:
1. спасибо за ваше предложение, я использую CORS-Anywhere и добавляю скрипты для прокси с
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); });
2. кроме того, я создаю
const proxy='http://127.0.0.1:8080/'
и извлекаю (прокси url), поэтому он работает сейчас, но порт должен использовать 8080,