Ich habe einen node.JS Express-Server erstellt, der über die API JSON an mein Frontend sendet. Ich habe das Backend fertiggestellt und auf einen AWS-Server gestellt. Jetzt m?chte ich nur noch am React-Frontend arbeiten. Ich beginne auf ?localhost:3000“ zu reagieren und stelle eine Anfrage an den AWS-Server, erhalte jedoch eine CORS-Fehlermeldung, die mir mitteilt, dass ?localhost:3000“ nicht berechtigt ist, Anfragen an diesen Server zu senden.
從源“http://localhost:3000”獲取“http://www.myawssever.fr:4000/api-url/”的訪問已被 CORS 策略阻止:無“訪問控制” -Allow-Origin'標頭存在于請求的資源上。如果不透明響應滿足您的需求,請將請求模式設(shè)置為“no-cors”以在禁用 CORS 的情況下獲取資源。
Ich habe mehrere L?sungen ausprobiert, um localhost:3000 zu autorisieren, aber ich glaube nicht, dass das Problem von dort kommt, denn für den Server ist localhost:3000 die Adresse selbst! Wissen Sie, wie ich meinen Rücken von meinem Computer aus testen kann (Reagieren auf localhost:3000), indem ich eine Anfrage an den Server (AWS) sende?
以下是解決 CORS 錯誤并啟用 React 前端與 AWS 服務器之間通信的組合步驟
在您的 AWS 服務器上配置 CORS
首先,您需要配置服務器以在響應
中包含適當?shù)?code>CORS標頭。您需要添加帶有值“http://localhost:3000”的“Access-Control-Allow-Origin”標頭,以允許來自React應用程序的請求。
配置CORS的具體方法
配置 CORS 的確切方法取決于您使用的服務器技術(shù)(例如 Express、Apache、Nginx)。例如,如果您使用 Express,則可以使用 cors 中間件。以下是如何使用 Express 配置 CORS 的示例:
const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors({ origin: 'http://localhost:3000' })); // Rest of your server code... app.listen(4000, () => { console.log('Server running on port 4000'); });
重新啟動您的 AWS 服務器
配置 CORS 后,重新啟動 AWS 服務器以應用更改。