繁体   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