CORS问题-“所请求的资源上没有'Access-Control-Allow-Origin'标头。”

时间:2018-06-26 14:07:21

标签: javascript php mysql cors

因此,我一直在尝试将数据从前端传递到后端(但是,我在该领域经验不足)。数据通过,但是,如果我尝试通过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插入,数据将返回到前端。我在这里停留了一段时间,现在正在各种论坛中寻找解决方案。该错误消息表明标题不存在,但您可以看到。

任何帮助将不胜感激!

干杯!

3 个答案:

答案 0 :(得分:1)

下午好,这是因为apache阻止了来自不同来源的请求,即,如果您的后端位于 http://yourdomain.com/client ,而字体的末端位于 localhost:3001 会导致a,因为它们的来源不同(宿主)。

解决:

在您的api /后端文件夹中使用.htaccess文件,例如,在我的应用程序中,我的index.php不在localhost / my-api / public目录中,那么我的.htaccess文件不在此目录目录localhost / my-api中/公开

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

答案 1 :(得分:0)

JavaScript和PHP中的CORS的工作原理类似。

  1. OPTIONS 方法请求将从浏览器端触发。
  2. 服务器端(PHP)应该通过响应“确定” 来接受 OPTIONS 请求。
  3. 现在,将从浏览器端触发适当的POST请求,该请求将转到您的功能位置,在该位置将执行PHP代码。

    如果($ _SERVER [“ REQUEST_METHOD”] ===“ OPTIONS”){    //您可以处理请求并做出响应的位置    回显“ OK”; }

答案 2 :(得分:0)

如果您无法控制服务器端,则可以像我一样在

上解决

仅客户端。

如果可以控制服务器端,则可以使用服务器端解决方案。我在这里没有讨论。

仅在客户端,解决方法是

使用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