【问题标题】:CORS issue posting domain A to domain BCORS 问题将域 A 发布到域 B
【发布时间】:2019-10-05 08:11:04
【问题描述】:

我只在 axios 上遇到了 CORS 问题。

在这个 html 页面中,我使用传统的表单从域 A 发布到域 B。

表单提交工作正常。 ajax 发布请求正常工作。 axios 帖子将我返回到 CORS。

从源 'http://domainA.com' 访问 XMLHttpRequest 在 'https://domainB/post.php' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow-Origin ' 请求的资源上存在标头

<html>
<head>
    <title>Registration Form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://npmcdn.com/axios/dist/axios.min.js"></script>
<body>

    <h2>Registration Form</h2>

    <form action="https://domainB.com/post.php" method="POST">

        Last name:

        <input type="text" name="username"> 

        <input type="hidden" name="form_submitted" value="1" />

        <input type="submit" value="Submit">

    </form>

    <script>
        $(document).ready(function(){
    $.post("https://domainB.com/post.php",
    {
      username: "Donald Duck",
      city: "Duckburg"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
});
    </script>
    <script>

(function() {

axios.post('https://domainB.com/post.php', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


})();

</script>
</body>
</html>

我的帖子.php

<?php
echo 'post working';
var_dump( $_POST);
 $_POST['username'];
?>

【问题讨论】:

    标签: php jquery ajax axios


    【解决方案1】:

    CORS 由后端控制。

    浏览器阻止您的代码访问响应,因为浏览器在响应中看不到 Access-Control-Allow-Origin

    使用 CORS 会向服务器发出预检请求,以查看该请求是否被允许。您需要通过设置标题Acces-Control-Allow-Origin: * 来让您的服务器响应以OPTIONS 作为请求方法的请求,这将允许来自任何来源的请求。或者,您可以只允许某些来源Acces-Control-Allow-Origin: http://example.com.

    通过代理发出请求仍然可以正常工作,代理可以代表您的请求发送适当的 CORS 标头。

    const proxy = "https://cors-anywhere.herokuapp.com/";
    const url = "https://domainB.com/post.php"; 
    fetch(proxy + url)
      .then(response => response.text())
      .then(contents => console.log(contents))
      .catch(() => console.log("CORS Error" + url ))

    通过代理发出请求将以这种方式工作

    1. CORS 代理会将您的请求转发至https://domainB.com/post.php
    2. 来自https://domainB.com/post.php 的返回响应带有Access-Control-Allow-Origin 标头。
    3. 现在您的浏览器可以在响应标头中看到 Access-Control-Allow-Origin 标头。

    更详细的解释你可以看看这个

    https://stackoverflow.com/a/43881141/2850383

    【讨论】:

      【解决方案2】:

      服务器有配置。我没有做任何事情,并坚持与托管公司合作。他们能够修复它。

      【讨论】:

        猜你喜欢
        • 2012-03-04
        • 2018-08-31
        • 2017-11-25
        • 1970-01-01
        • 2017-03-23
        • 2020-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多