php 如何在 XAMPP 上启用跨域资源共享?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34872760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:15:42  来源:igfitidea点击:

How do I enable cross-origin resource sharing on XAMPP?

phpapachecross-domainconfig

提问by alex

I have a html file on my localhost with a form and jquery/ajax which handles the post data. A simple php script looks up the data in a mysql database table

我的本地主机上有一个 html 文件,其中包含一个表单和处理发布数据的 jquery/ajax。一个简单的php脚本在mysql数据库表中查找数据

This is the main part:

这是主要部分:

// $.post('lookup_update.php', $(this).serialize()) //<- local part which works
   $.post('http://www.example.com/projectX/lookup_update.php', $(this).serialize()).done(function (data)
                            { etc.

But when I point to the online lookup_update.php I get the following error message in chrome

但是当我指向在线 lookup_update.php 时,我在 chrome 中收到以下错误消息

XMLHttpRequest cannot load http://www.example.com/projectX/lookup_update.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.

XMLHttpRequest 无法加载http://www.example.com/projectX/lookup_update.php。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost'。响应具有 HTTP 状态代码 404。

As I understand it I need to use

据我了解,我需要使用

 header("Access-Control-Allow-Origin: *");

for php. But when I add this to example.com/lookup_update.php, the file gives a 404 when the localhost file tries to call it.

对于 php。但是当我将它添加到 example.com/lookup_update.php 时,当 localhost 文件尝试调用它时,该文件会给出 404。

I also tried to add the following to my Xampp apache config file

我还尝试将以下内容添加到我的 Xampp apache 配置文件中

Header set Access-Control-Allow-Origin "*"

How do I correctly enable cross-origin resource from my local XAMPP setup??

如何从我的本地 XAMPP 设置中正确启用跨源资源?

[EDIT] This is my simple form on my localhost

[编辑]这是我在本地主机上的简单表格

<!--Begin form-->
    <div id="form" class="result">
        <form method="post" id="reg-form"  class="form-horizontal">
            <div class="controls">
                <input type="text" name="code" id="code" placeholder="Code"  class="form-control input-lg" />      
            </div>
        </form>
    </div>
    <!--End form-->

With the following form jquery code

使用以下表单 jquery 代码

    <script type="text/javascript">
            $(document).ready(function ()
            {
                $(document).on('submit', '#reg-form', function ()
                {
                    var tmpCode = $("#code").val();

//                    $.post('lookup_update.php', $(this).serialize())
                      $.post('http://www.example.com/projectX/lookup_update.php', $(this).serialize())
                            .done(function (data)
                            {

                                $("#reg-form").fadeOut('slow', function ()
                                {
                                    $(".result").fadeIn('slow', function ()
                                    {
                                        console.log("inner test " + tmpCode);
                                        $(".result").html(data);


                                        setTimeout(function () {
                                            location.reload();
                                            $('input').val("");
                                        }, 3000);


                                    });
                                });
                            })
                            .fail(function ()
                            {
                                alert('fail to submit the data');
                            });
                    return false;
                });


            });

        </script>

[EDIT 2]

[编辑2]

OK, i don't think it has to do with the online lookup_update.php file, as I am using this to test in another file

好的,我认为它与在线 lookup_update.php 文件无关,因为我正在使用它在另一个文件中进行测试

            var testXHR = $.post("http://www.example.com/projectX/lookup_update.php", function (data) {
            alert("success:" + data);
        })

And in the alert popup window I see the expected data

在警报弹出窗口中,我看到了预期的数据

采纳答案by Monty

You have to write below code at the beginning of your lookup_update.php

您必须在 lookup_update.php 的开头编写以下代码

header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');

Instead of * you can write just Ip address.

你可以只写IP地址而不是*。

OR

或者

First you have to check where is problem either on localhost or other server.

首先,您必须检查本地主机或其他服务器上的问题在哪里。

Try this code :If you getting some data in alert then problem is on localhost else on other server.

试试这个代码:如果你在警报中得到一些数据,那么问题出在其他服务器上的本地主机上。

$.post( "test.php", function( data ) {
alert( "Data Loaded: " + data );
});

回答by Slytherin

CORS requests are "secured" with preflightrequests.

CORS 请求由预检请求“保护” 。

MDN talks about it here

MDN在这里谈论它

Additionally, for HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method

此外,对于可能对用户数据产生副作用的 HTTP 请求方法(特别是对于 GET 以外的 HTTP 方法,或者对于某些 MIME 类型的 POST 使用),规范要求浏览器“预检”请求,请求支持的方法使用 HTTP OPTIONS 请求方法从服务器发送,然后在服务器“批准”后,使用实际 HTTP 请求方法发送实际请求

This is just a guess here, but you are probably using a framework, and you forgot to enable (implement) OPTIONS route for your requests.

这只是一个猜测,但您可能正在使用一个框架,并且您忘记为您的请求启用(实现)OPTIONS 路由。

Worth noting, you shouldn't use the wildcard header ( allowing any site to CORS your service ), you should rather specify a whitelist.

值得注意的是,您不应使用通配符标头(允许任何站点对您的服务进行 CORS),而应指定白名单。

Another header that you should be sending is allowed request method.

您应该发送的另一个标头是允许的请求方法。

Access-Control-Request-Method: POST

Hope this helps.

希望这可以帮助。

回答by ViníciusPJ

If you want to allow CORS in the httpd.conffile this is what worked for me:

如果您想在httpd.conf文件中允许 CORS,这对我有用:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "X-Requested-With, Content-Type, X-Token-Auth, Authorization"

Put it below the Listen 80line in the httpd.conffile.

将其放在文件中的Listen 80行下方httpd.conf

When I used only Header set Access-Control-Allow-Origin "*"GETrequests worked, but POSTdidn't.

当我只使用Header set Access-Control-Allow-Origin "*"GET请求时,请求有效,但POST没有。

The enviroment it was tested is Windows 10 on Apache server using XAMPP. Apache is hosting a Laravel project.

它测试的环境是使用 XAMPP 的 Apache 服务器上的 Windows 10。Apache 正在托管一个 Laravel 项目。