使用 WordPress 将表单数据传递到 API 自定义路由

Passing form data to API custom route with WordPress

在拨打 API 电话时收到以下 500 代码响应:PUT https://my-site.com/wp/wp-json/contact/v1/send 500

functions.php 中,我的 WP 自定义路由是这样定义的:

function sendContactMail(WP_REST_Request $request) {
}

add_action('rest_api_init', function () {
  register_rest_route( 'contact/v1', 'send', array(
    'methods' => 'PUT',
    'callback' => 'sendContactMail'
  ));
});

以下是我如何拨打 API 电话:

formData.append('contact_name', this.contactName)
formData.append('contact_email', this.contactEmail)
formData.append('contact_message', this.contactMessage)

this.$axios.$put('https://my-site.com/wp/wp-json/contact/v1/send', formData)
  .then((res) => {
    this.ApiResponse = res
  })
  .catch((err) => {
    this.$toast.error(err.response)
  })

为什么我会收到 500 错误?

像这样更新函数

function sendContactMail(WP_REST_Request $request) {
}

add_action('rest_api_init', function () {
  register_rest_route( 'contact/v1', '/send', array(
    'methods' => 'PUT',
    'callback' => 'sendContactMail'
  ));
});

像这样更新函数

formData.append('contact_name', this.contactName)
formData.append('contact_email', this.contactEmail)
formData.append('contact_message', this.contactMessage)

this.$axios.$put('https://my-site.com/wp-json/contact/v1/send', formData)
  .then((res) => {
    this.ApiResponse = res
  })
  .catch((err) => {
    this.$toast.error(err.response)
  })

问题很可能是回调函数需要一个 return 值。在 function sendContactMail(WP_REST_Request $request) { } 结束时,您需要 return a WP_REST_Response or WP_Error 发回回复。

我在这里建立了一个简单的小例子:https://xhynk.com/content-mask/65451758-answer/

“点击我(坏)”和“点击我(好)”按钮做的事情完全一样,只是改变了发送的数据。 sendContactMail() 函数的唯一区别如下:

function sendContactMail(WP_REST_Request $request) {
  if( $request->get_body() == 'return=true' ){
    return new WP_REST_Response(
      array(
        'status' => 200,
        'response' => 'Did the thing'
      );
    );
  }
}

“真”条件仅在单击“好”按钮时触发,这是处理 .done() 块的地方,而“坏”按钮触发 .catch 块。

因此,您应该能够通过对数据执行 X、Y、Z 并确保返回正确的响应来解决问题

还要确保您没有 运行 陷入 PHP 错误(比如直接访问 $request 属性,因为它们是 protected 属性,并执行类似 if( $request->body == 'something' ) 的操作将触发“PHP 致命错误:无法访问受保护的 属性” 并提供 500 错误。

Bug 进行我的 API 调用 JS 脚本
因此,从 URL 中删除多余的 wp,然后更新 URL 将看起来像
https://my-site.com/wp-json/contact/v1/send

更新后的脚本如下所示

formData.append('contact_name', this.contactName)
formData.append('contact_email', this.contactEmail)
formData.append('contact_message', this.contactMessage)

this.$axios.$put('https://my-site.com/wp-json/contact/v1/send', formData)
 .then((res) => {
 this.ApiResponse = res
})
.catch((err) => {
 this.$toast.error(err.response)
});