简体   繁体   English

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

[英]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: 数据通过,但是,如果我尝试通过PDO将数据插入到MySQL-DB中,浏览器将显示以下错误:

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. 无法加载http:// localhost:8888 / post_recipe.php :对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。 Origin ' http://localhost:3000 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:3000 '。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." 如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。”

JS 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

 <?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. 因此,如果删除MySQL插入,数据将返回到前端。 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. 下午好,这是因为apache阻止了来自不同来源的请求,即,如果您的后端位于http://yourdomain.com/client上,而您的font-end位于localhost:3001上,则会导致a,因为它们是不同的(主机)起源。

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

Or config in apache.conf 或在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. Java和CORS中的CORS的工作原理类似。

  1. OPTIONS method request will be triggered from browser side. OPTIONS方法请求将从浏览器端触发。
  2. Server side (PHP) should accept the OPTIONS request, by responding 'OK' . 服务器端(PHP)应该通过响应“ OK”来接受OPTIONS请求。
  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. 现在,将从浏览器端触发正确的POST请求,该请求将转到您的功能位置,在该位置将执行PHP代码。

    if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") { //location where you can handle your request and respond ok echo 'OK'; if($ _SERVER [“ REQUEST_METHOD”] ===“ OPTIONS”){//您可以处理请求并响应的位置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', 使用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.

相关问题 CORS 策略:请求的资源上不存在“Access-Control-Allow-Origin”标头。 在 reactjs 中使用 iframe 时 - CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. while using iframe in reactjs 请求的资源上不存在 Access-Control-Allow-Origin header。 将请求的模式设置为 no-cors 以获取禁用 CORS 的资源 - 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所请求的资源上没有“ Access-Control-Allow-Origin”标头 - CORS No 'Access-Control-Allow-Origin' header is present on the requested resource 被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”header。 Java 带有 CrossOrigin("*") 注释的后端 - Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Java Backend with CrossOrigin("*") annotation CORS 政策阻止了获取“url”的访问:请求的资源上不存在“Access-Control-Allow-Origin”header。 ReactJS - Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS Golang 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此不允许访问原点 &#39;null&#39; - Golang No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 因此,不允许访问源“ file://”。 - No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file://' is therefore not allowed access. 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 因此,不允许访问原始“空” - No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access 请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin &#39;...&#39; 因此不允许访问 - No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access 如何修复“http://localhost:3000”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”header。 - 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