WordPress REST API POST 请求返回空对象的解决方案

wordpress rest api post 请求返回空对象的解决方案

本文将围绕解决 WordPress Gutenberg block 开发中,使用 wp.apiFetch 发送 POST 请求到自定义 REST API 接口时,服务器端接收到的数据为空对象的问题展开。通过示例代码和详细解释,帮助开发者理解并解决此问题,确保数据正确传递。

在 Gutenberg block 开发中,经常需要通过 REST API 与服务器进行数据交互。wp.apiFetch 是 WordPress 提供的便捷的 API 请求工具。然而,在使用 wp.apiFetch 发送 POST 请求时,有时会遇到服务器端接收到的数据为空对象的情况,导致功能无法正常实现。

问题原因分析

出现该问题的主要原因是 wp.apiFetch 默认的 Content-Type 与服务器端期望的 Content-Type 不一致。默认情况下,wp.apiFetch 可能不会自动设置 Content-Type 为 application/json,导致服务器无法正确解析请求体中的 JSON 数据。

解决方案

解决该问题的关键在于显式地设置 Content-Type 为 application/json。可以通过在 wp.apiFetch 的 headers 选项中指定 Content-Type 来实现。

示例代码

以下是修改后的 Edit.js 文件示例代码:

wp.apiFetch({
  path: '/name-support/v1/zipped/',
  method: 'POST',
  headers: {
    "Content-Type": "application/json",
  },
  data: { id: 'test test test' },
}).then(data => {
  console.log('response: ', data);
});
登录后复制

代码解释

  • headers: { “Content-Type”: “application/json” }: 这部分代码显式地设置了请求头的 Content-Type 为 application/json,告诉服务器请求体中的数据是 JSON 格式。

服务器端代码

以下是 REST API 路由设置和回调函数的示例代码:

add_action( 'rest_api_init', function () {
  register_rest_route( 'name-support/v1', '/zipped/', 
      [
        'methods' => WP_REST_Server::EDITABLE,
        'callback' => 'name_image_sequence_unzip',
        'permission_callback' => '__return_true'
      ] 
  );
});

function name_image_sequence_unzip($data) {
    return rest_ensure_response( $data );
}
登录后复制

注意事项

  • 确保服务器端能够正确处理 application/json 格式的请求。
  • 在开发环境中,可以通过浏览器开发者工具的网络面板查看请求头,确认 Content-Type 是否已正确设置。
  • 如果服务器端使用了中间件或插件对请求进行了处理,需要检查这些中间件或插件是否会影响 Content-Type 的设置。

总结

通过显式地设置 wp.apiFetch 请求的 Content-Type 为 application/json,可以有效解决 POST 请求返回空对象的问题。在实际开发中,应根据服务器端的要求设置正确的 Content-Type,确保数据能够正确传递和解析。 此外,使用浏览器开发者工具可以帮助你调试 API 请求,确认问题所在。

以上就是WordPress REST API POST 请求返回空对象的解决方案的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1464515.html

发表回复

Your email address will not be published. Required fields are marked *