0

在这里,我尝试使用Medium API从我的 WordPress 前端表单在我的Medium个人资料上创建新帖子。

jQuery(document).ready(function ($) {

    function get_tinymce_content(){
        if (jQuery("#wp-mediumcontenteditor-wrap").hasClass("tmce-active")){
            return tinyMCE.activeEditor.getContent();
        }else{
            return jQuery('#mediumcontenteditor').val();
        }
    }

    function formToJSON() {
        return JSON.stringify({
            "title": $('#m_title').val(),
            "contentFormat": 'html',
            "content": get_tinymce_content(),
            "tags": ["football", "sport", "Liverpool"],
            "publishStatus": 'public'
            });
    }

    // Perform AJAX
    $('form#medium').on('submit', function(e){
        $('p.status', this).show().text(ajax_magic_kuira.loadingmessage);
        ctrl = $(this);
        $.ajax({
            xhrFields: {
                withCredentials: true
            },
            type: 'POST',
            url: 'https://api.medium.com/v1/users/xxxuserID/posts',
            dataType: 'json',
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            data: formToJSON(),
            beforeSend: function (xhr) {
                xhr.setRequestHeader ("Authorization", "Bearer xxxxToken");
            },
            headers: {
                "Access-Control-Allow-Headers": 'Origin',
                'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
                'Access-Control-Allow-Credentials': true,
                'Access-Control-Allow-Origin': 'http://demopress.xyz' // my domain where I make the ajax request.
            },
            success: function(data, textStatus, jqXHR){
                alert('Successfully Request Send!!');
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert('Sorry -- Error');
            }
        });
        e.preventDefault();
        return false;
    });

});

但无法通过 ajax 发送数据。每次我收到错误时提交我的表单后Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.medium.com/v1/users/xxxuserID/posts. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Ajax 头文件截图

我尝试了我在网上找到的所有解决方案,但还没有运气。这是我试图解决这个问题的一些解决方案。

  1. https://www.html5rocks.com/en/tutorials/cors/
  2. https://stackoverflow.com/a/3506306/3967385
  3. https://zinoui.c​​om/blog/cross-domain-ajax-request
  4. http://www.ajax-cross-origin.com/
  5. ETC

当我通过 REST API 将这些解决方案用于GET(从服务器检索数据)数据时,它可以正常工作并且GET无需使用任何技巧即可工作。意味着如果我想从另一个域检索数据,它工作正常,但是当我使用POST/PUT方法创建或发送新数据到另一台服务器时,它不工作并重放同样的错误。

注意:我可以通过使用成功发送数据,php但我不想在这里使用 php 和核心 javascript。我只想使用 jQuery/ajax 完成这项任务。

这是我的问题:

  1. 可以仅使用带有 REST API 的 jquery/ajax 发布另一台服务器(就像我想在我的中型个人资料上创建一个新帖子)
  2. 如果可能,那怎么办?请与 REST API 分享至少一个示例
4

2 回答 2

0

服务器必须响应Allow-Control-Allow-*标头而不是您的 Web 应用程序。

Access-Control-Allow-Origin : https://www.yourowndomain.com

当浏览器没有收到来自服务器的上述标头时,请求将被浏览器阻止。

我没有任何使用 Medium 的经验,但我相信您的帐户尚未获得访问其 API 的权限。

于 2016-10-21T01:09:54.407 回答
0

尝试这个:

add_filter( 'wp_headers', 'send_cors_headers', 11, 1 );
function send_cors_headers( $headers ) {
    $headers['Access-Control-Allow-Origin'] = $_SERVER[ 'HTTP_ORIGIN' ];
    return $headers;
}

请注意,这将允许从任何来源进行访问。为了安全起见,您应该尝试设置一组允许的域,这些域可以向您的 WordPress 站点发出请求,如果发出请求的域不在允许列表中,则短路允许 CORS:

add_filter( 'wp_headers', 'send_cors_headers', 11, 1 );
function send_cors_headers( $headers ) {
    $allowed_domains = array( 'https://my.okdomain.com' , 'http://anothergoodone.com');
    if ( ! in_array( $_SERVER[ 'HTTP_ORIGIN' ] , $allowed_domains ) ) return $headers;
    $headers['Access-Control-Allow-Origin'] = $_SERVER[ 'HTTP_ORIGIN' ];
    return $headers;
}
于 2019-04-04T16:30:25.443 回答