为啥离子中的WP rest API在模拟器中不起作用

Posted

技术标签:

【中文标题】为啥离子中的WP rest API在模拟器中不起作用【英文标题】:Why WP rest API in ionic does not work in emulator为什么离子中的WP rest API在模拟器中不起作用 【发布时间】:2021-02-17 19:56:42 【问题描述】:

我创建了一个适用于 ionic 应用程序的 WP rest API。可以在我的本地主机上工作,但是当我在 iphone 模拟器中运行该应用程序时,它不起作用。 WP REST API 不再显示内容。

可能是什么问题?

【问题讨论】:

你试过调试吗?是否显示任何错误? 如果是 Iphone,请通过 Safari 浏览器调试您的模拟器。并查看您的控制台以了解错误。 【参考方案1】:

默认情况下,WordPress 控制允许访问框架的协议(http://....、ftp://.....)以实现安全措施 (https://tommcfarlin.com/what-is-wordpress-kses/)。

在调试或生产模式下在设备上运行 ionic 应用程序时,它将请求的来源指定为 ionic://localhost。然后,您必须告诉 WP 接受来自该来源的请求。

将此代码放在主题的 functions.php 中,因为它将解决 ios HTTP 请求到 WP REST API 的问题:

// Adding ionic Protocol Start.

add_filter('kses_allowed_protocols', function ($protocols) 
    $protocols[] = 'ionic';
    return $protocols;
);

// Adding ionic Protocol End.

顺便说一句,如果您随时遇到 CORS 错误,请确保将此代码也放在 functions.php 中:

// Enabling CORS Start.
function handle_preflight()


    $origin = get_http_origin();

    header("Access-Control-Allow-Origin: " . $origin);

    // Specify the allowed HTTP methods.
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Headers: Authorization, Content-Type');

    if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) 
        status_header(200);
        exit();
    


add_action('init', 'handle_preflight');

function add_cors_http_header()

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");


add_action('init', 'add_cors_http_header');

// Enabling CORS End.

【讨论】:

以上是关于为啥离子中的WP rest API在模拟器中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Wordpress 使用自定义端点 rest api 上传多个图像(离子作为最终用户)

快速将 REST API 中的 JSON 数据填充到表格视图中不起作用

WP REST API V2 不起作用

JSON stringify 中的变量在 Rest 请求中不起作用

raise PermissionDenied 中的自定义消息在 Django rest 中不起作用

为啥 setLandingPageType("billing") 在沙盒中工作,但在 PAYPAL PHP REST API SDK WebProfile 中的实时版本中不工作