![](/img/trans.png)
[英]How to fix CORS error when sending a request to express server from react app
[英]CORS error when posting request in React app to PHP file in Apache server on localhost
我正在創建一個簡單的應用程序,用於從一個站點獲取 icos 和公司名稱。 我已經用 JQuery 完成了這個項目,現在我正在嘗試學習 React 並在其中做同樣的事情。
該項目的第一部分是帶有 ico 和名稱輸入的表單。 提交時,它會向 php 文件創建發布請求,該文件檢查插入的值是否在數據庫中,如果是,則檢查它們是否小於 1 個月。 之后,它從數據庫或網站(從網站是最新的)返回行。
但我有一個小問題。 我無法使用 React 創建發布請求,因為此錯誤: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.0.52:80/backend/backend.php. (Reason: header 'access-control-allow-origin' is not allowed according to header 'Access-Control-Allow-Headers' from CORS preflight response).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.0.52:80/backend/backend.php. (Reason: header 'access-control-allow-origin' is not allowed according to header 'Access-Control-Allow-Headers' from CORS preflight response).
我在端口 80 上運行 WampServer,這是我的后端。php 文件和 React 應用程序的另一個可怕之處。 在 WampServer 中是 headers_module,它已啟用,在 php 文件中是 header header('Access-Control-Allow-Origin: *');
. 在 axios 發布請求中,我也包括"Access-Control-Allow-Origin": "*"
。 請問有人知道,如何解決這個問題? 我想不通。
這是我的 axios 代碼片段:
const options = {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
}
};
axios.post("http://192.168.0.52:80/backend/backend.php", {
ico: this.state.ico,
name: this.state.name,
searchFirm: true
}, options)
.then((response) => {
}, (error) => {
});
這是 php 文件的片段:
<?php
header('Access-Control-Allow-Origin: *');
require_once "DbConnect.php";
echo "ahoj";
...
瀏覽器中的http://192.168.0.52:80/backend/backend.php工作正常。
編輯:但有趣的是,當我發送請求時,它在 net 選項卡中返回兩行,當我打開第二行並在右上角單擊“再次發送”時,它通過了。
經過幾天的搜索,我想出了一個解決方案。 希望它會幫助某人。
您需要做的就是將這兩行添加到 php 文件中:
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: Content-Type');
在 axios 請求中,您不需要使用標頭,因此它看起來像這樣:
axios.post("your_url", {
your_data
})
.then((response) => {
}, (error) => {
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.