WordPress API 路由无法访问

WordPress API route unreachable

当使用我的 WordPress 自定义路由调用 Axios put() 方法时,我在控制台中收到此错误:

PUT http://my-project.com/wp/wp-json/contact/v1/send 404 (Not Found)

以下是我在 WP 中定义自定义路由的方式 functions.php:

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

这是我应用中的调用 (Vue.js):

this.$axios.$put(`${this.baseUrl}/wp-json/contact/v1/send`, formData)
  .then((res) => {
    this.success = true
  })
  .catch((err) => {
    this.$toast.error(err.response)
  })

我做错了什么?

register_rest_route 调用的 methods 部分,只允许使用 POST 方法,但您的代码使用的是 PUT.

您可以将 axios 调用更改为 axios.post 或在路由定义中添加 PUT 方法。为此,更改 methods,它可以是逗号分隔的 HTTP 方法字符串或字符串数​​组,例如:

'methods' => 'POST,PUT',

'methods' => ['POST','PUT'],