简体   繁体   中英

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

So I've been trying to pass data from my front-end to my back-end (however, I'm not very experienced within this area). The data comes through, however, if I try to insert the data into my MySQL-DB through PDO the browser gives me the following error:

Failed to load http://localhost:8888/post_recipe.php : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:3000 ' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

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); ?> 

So if I delete the MySQL-insertion, the data comes back to the front-end. I have been stuck here for a while now searching various forums for a solution. The error message says that the header is not present, however it is there, as you can see.

Any help would be much appreciated!

Cheers!

Good afternoon, this is because of the apache blocking requests from different sources ie if your backend is at http://yourdomain.com/client and your font-end is at localhost:3001 will cause a because they are of different (host) origins.

To solve:

Use the .htaccess file in your api / backend folder, for example, in my application my index.php is not in localhost / my-api / public directory then my .htaccess file in this directory directory 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>

Or config in 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)

CORS in Javascript and PHP works like.

  1. OPTIONS method request will be triggered from browser side.
  2. Server side (PHP) should accept the OPTIONS request, by responding 'OK' .
  3. Now a proper POST request will be triggered from browser side, which will go to your functionality location where your PHP code will gets executed.

    if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") { //location where you can handle your request and respond ok echo 'OK'; }

If you can not control the sever side, you can work around like me on

Client side only.

If you can control server side, you can use server side solution. I am not discus it here.

Only on client side, work around is

use 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               

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. while using iframe in reactjs No Access-Control-Allow-Origin header is present on the requested resource. set the request's mode to no-cors to fetch the resource with CORS disabled CORS No 'Access-Control-Allow-Origin' header is present on the requested resource Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Java Backend with CrossOrigin("*") annotation Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS Golang No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file://' is therefore not allowed access. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access How to fix ''http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM