簡體   English   中英

CORS問題-“所請求的資源上沒有'Access-Control-Allow-Origin'標頭。”

[英]CORS-issue - “No 'Access-Control-Allow-Origin' header is present on the requested resource.”

因此,我一直在嘗試將數據從前端傳遞到后端(但是,我在該領域經驗不足)。 數據通過,但是,如果我嘗試通過PDO將數據插入到MySQL-DB中,瀏覽器將顯示以下錯誤:

無法加載http:// localhost:8888 / post_recipe.php :對預檢請求的響應未通過訪問控制檢查:所請求的資源上沒有'Access-Control-Allow-Origin'標頭。 因此,不允許訪問源' http:// localhost:3000 '。 如果不透明的響應滿足您的需求,請將請求的模式設置為“ no-cors”,以在禁用CORS的情況下獲取資源。”

JS

 postToAPI = () => { fetch(`http://localhost:8888/post_recipe.php`, { method: 'POST', headers: { 'Content-Type': 'text/html' }, mode: 'cors', body: JSON.stringify({ title: this.state.title, description: this.state.description, userID: this.props.userInfo.response.id, name: this.props.userInfo.response.name, stepByStep: (this.state.stepByStep), recipeIngredients: (this.state.recipeIngredients), profileImg: this.props.userInfo.response.picture.data.url }) }) .then((response) => response.json()) .then((fetch) => { console.log(fetch) }); } 

PHP

 <?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Credentials: true'); header("Content-type: text/html; charset=utf-8"); header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token'); $post = json_decode(file_get_contents('php://input')); $array = json_decode(json_encode($post), True); $pdo = new PDO( "mysql:host=localhost:8889;dbname=veganify;charset=utf8", "root", "root" ); $statement = $pdo->prepare( "INSERT INTO posts (title, description, userID, name, stepByStep, recipeIngredients, profileImg) VALUES (:title, :description, :userID, :name, :stepByStep, :recipeIngredients, :profileImg)" ); $statement->execute(array( ":title" => $array["title"], ":description" => $array["description"], ":userID" => $array["userID"], ":name" => $array["name"], ":stepByStep" => $array["stepByStep"], ":recipeIngredients" => $array["recipeIngredients"], ":profileImg" => $array["profileImg"] )); } echo json_encode($array); ?> 

因此,如果刪除MySQL插入,數據將返回到前端。 我在這里停留了一段時間,現在正在各種論壇中尋找解決方案。 錯誤消息顯示標題不存在,但在那里,如您所見。

任何幫助將非常感激!

干杯!

下午好,這是因為apache阻止了來自不同來源的請求,即,如果您的后端位於http://yourdomain.com/client上,而您的font-end位於localhost:3001上,則會導致a,因為它們是不同的(主機)起源。

解決:

使用您的api /后端文件夾中的.htaccess文件,例如,在我的應用程序中,我的index.php不在localhost / my-api / public目錄中,那么我的.htaccess文件在此目錄目錄localhost / my-api / public中

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Origin: "*" (allow access from any origin)
Header set Access-Control-Allow-Origin: "http://motech-ui.example" (allow access from only "http://motech-ui.example" origin)
Access-Control-Allow-Origin: "http://motech-ui.example | http://other.domain" (allow access from two mentioned origins)
</IfModule>

或在apache.conf中進行配置

Access-Control-Allow-Origin: "*" (allow access from any origin)
Access-Control-Allow-Origin: "http://motech-ui.example" (allow access from only "http://motech-ui.example" origin)
Access-Control-Allow-Origin: "http://motech-ui.example | http://other.domain" (allow access from two mentioned origins)

Java和CORS中的CORS的工作原理類似。

  1. OPTIONS方法請求將從瀏覽器端觸發。
  2. 服務器端(PHP)應該通過響應“ OK”來接受OPTIONS請求。
  3. 現在,將從瀏覽器端觸發正確的POST請求,該請求將轉到您的功能位置,在該位置將執行PHP代碼。

    if($ _SERVER [“ REQUEST_METHOD”] ===“ OPTIONS”){//您可以處理請求並響應的位置ok echo'OK'; }

如果您無法控制服務器端,則可以像我一樣解決

僅客戶端。

如果可以控制服務器端,則可以使用服務器端解決方案。 在這里我不討論。

僅在客戶端,解決方法是

使用dataType:'jsonp',

   async function get_ajax_data(){

       var _reprojected_lat_lng = await $.ajax({

                                type: 'GET',

                                dataType: 'jsonp',

                                data: {},

                                url: _reprojection_url,

                                error: function (jqXHR, textStatus, errorThrown) {

                                    console.log(jqXHR)

                                },

                                success: function (data) {

                                    console.log(data);



                                    // note: data is already json type, you just specify dataType: jsonp

                                    return data;

                                }

                            });





 } // function               

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM