【问题标题】:XMLHttpRequest Issue has been blocked by CORS policy:XMLHttpRequest 问题已被 CORS 策略阻止:
【发布时间】:2021-10-27 19:12:23
【问题描述】:

我在 codepen 中有这段代码,它可以正常工作,但是如果我将此代码作为插件安装在 wordpress 网站上,它会在下面显示此错误。

从“https://vative.us15.list-manage.com/subscribe/post”访问 XMLHttpRequest(重定向自“http://vative.us15.list-manage.com/subscribe/post”)源“http://localhost:8888”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我的代码笔在这里。

https://codepen.io/gegejosper/pen/powzGQJ?editors=1011

$.ajax({
            type: "post",
            url: "https://vative.us15.list-manage.com/subscribe/post",
          
            dataType: "json",
          data: data_val,
        
            success: function(data) {
                $(".optin-form").hide();
                $(".optin-success").show();
            },
            //expected to be error in result.
            error: function(data){
              
              $(".optin-form").hide();
              $(".optin-success").show();
            }
        });

有没有办法解决这个问题?请帮忙。

【问题讨论】:

    标签: javascript ajax xmlhttprequest same-origin-policy


    【解决方案1】:

    从服务器端(您的 VPS)添加以下标头:

    Access-Control-Allow-Origin: *

    节点

    res.writeHead(200, {'Access-Control-Allow-Origin': '*'});
    

    PHP

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

    您还可以将某些域列入白名单,如here 所示:

    Access-Control-Allow-Origin: https://codepen.io

    欲了解更多信息,请查看MDN

    【讨论】:

      【解决方案2】:

      服务器 (https://vative.us15.list-manage.com) 必须允许跨源请求。截至目前,它不允许这样做。 (具体的解决方案取决于编写的语言服务器)

      我在 codeopen 中看到了同样的问题: index.html:1 从源“https://cdpn.io”访问“https://vative.us15.list-manage.com/subscribe/post”的 XMLHttpRequest 已被 CORS 策略阻止:无“访问-请求的资源上存在 Control-Allow-Origin' 标头。

      【讨论】:

        猜你喜欢
        • 2021-09-05
        • 2019-12-18
        • 2020-11-23
        • 2019-04-28
        • 2018-02-26
        • 2021-04-24
        • 2021-10-05
        • 2022-08-14
        • 2021-01-14
        相关资源
        最近更新 更多