我托管在github页面上的API如何接受CORS

问题描述 投票:0回答:1

我在 github 上托管一个非常简单的 Express 服务器,该服务器作为我的前端的代理。 我的前端托管在 Hostinger 上。 我的前端向我的后端发出请求,然后我的后端向 RIOT API 发出请求。

const express = require('express');
const PORT=3000;
const axios = require("axios");
var cors = require("cors");
const players = [];


const app = express();
const options = {
  origin: '*',
}
app.use(cors(options));

const API_KEY = "RGAPI-faeead12-e326-47cc-8bc3-a3744ab2f0de"

function getPLayer(id) {
  return axios.get("https://euw1.api.riotgames.com"+"/lol/league/v4/entries/by-summoner/"+id+"?api_key="+API_KEY)
          .then(response=>{
            return response.data
          }).catch(err=>err)
}

app.get('/allLeagues',async(req,res)=>{
  const ids = ["EdlXilkFBeCqLWp4ueTZKjHBulsPyjrev1Mxg2_2yCHtqNM","NooO92s_pLaIkxu1MfQ0JzevllBzPReNlVjCfUZMwt5e3T8","dEdvO_yJpEBWtoOrR5ML-3oydz45lyA26FaH430rNazDDfU","kBWF56OOLJ6cmolafDqtEWsupL0lwtb8Z-Vb6GJJGZIc2b8","KXdujJcXyRwtC49D-ir2O4lGKmgZdbkXQ_mNJ58FuNryc_Xl","6W2lrvTtLClCgxAvHgon13AqmC6vCkY9LkwLVZqCrN-lrF0","An0DMGGlDEh1jS5XloAmIxbRdae82gLz02LHVjZKgYRcjW0L","wY5fu_yH2msVoZGdoyz1mn3nsMOVwEltn-0kvpODWcjEqPoQy7hoQByqqg"]
  for(const id of ids) {
    const player = await getPLayer(id)
    players.push(player)
  }
  res.status(200).json(players)
  players.length=0;
})
  
app.listen(PORT,()=>{
  console.log(`Server running on port ${PORT}`)
  })

module.exports = app;

这是我前端的请求:

let requestAPI = $.ajax({
  type: "GET", // Méthode à employer POST, GET, PUT, DELETE
  url: urlAPI, // Cible du script coté serveur à appeler
  dataType: "json",
  contentType: "application/json",
  headers: {
    "Content-Type": "application/json",
    'Access-Control-Allow-Origin': '*',
  },
});

我的应用程序在本地运行良好,但每当我尝试在 github 上托管我的服务器时,我都会收到 Cors 错误

enter image description here

network

我尝试将 cors 添加到我的后端,使用通配符甚至我的完整来源。

javascript node.js cors
1个回答
-1
投票

“Response to preflight request does not pass access control check. It does not have HTTP ok status”:这表明预检请求(在实际请求之前发送的 OPTIONS 请求)返回不成功的状态代码,导致浏览器阻塞主要要求。

验证预检响应状态:

使用浏览器开发人员工具(“网络”选项卡)检查预检请求及其响应。 响应状态代码应为 200 OK,浏览器才能继续。 查找服务器端代码中可能导致非 200 响应的任何错误。

考虑附加标头:

如果您的应用程序发送 cookie 或身份验证标头,请确保在 cors 中间件中设置“credentials: true”。 您可能还需要根据应用程序的要求指定 Access-Control-Allow-Methods 和 Access-Control-Allow-Headers。

服务器端调试:

使用服务器上的控制台日志或调试工具来详细检查预检请求和响应标头。 检查是否有任何可能妨碍成功响应的错误或错误配置。 部署验证:

最后确保您的应用程序已正确部署在 GitHub Actions 上并可从 demo.com 访问。

© www.soinside.com 2019 - 2024. All rights reserved.