最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

404 error - REST API: No route was found matching the URL and request method

programmeradmin1浏览0评论

I'm having issues adding a custom REST API route to Wordpress. Using my own plugin, i've registered the route as followed:

add_action( 'rest_api_init', function() {
  register_rest_route( $namespace, 'handler_mijnenergie', array(
    'methods'   => '\WP_REST_Server::CREATABLE ',
    'callback'  => [ $this, 'handle_energie_data' ]
  ), false );
} );

When calling the namespace "/wp-json/watz/v1" I get a correct response in Postman that the route is shown.

However, when i try to access the route request directly, i get thrown a 404 error. So far I've tried:

  • Rewriting the permalinks
  • Using standard Wordpress .htaccess
  • Disabling plugins
  • Changing method/namespace & request
  • Testing other plugin routes like Yoast or Contact Form 7 (they work)

Any idea what could be causing the issue here and what I need to alter to get this working?

I'm having issues adding a custom REST API route to Wordpress. Using my own plugin, i've registered the route as followed:

add_action( 'rest_api_init', function() {
  register_rest_route( $namespace, 'handler_mijnenergie', array(
    'methods'   => '\WP_REST_Server::CREATABLE ',
    'callback'  => [ $this, 'handle_energie_data' ]
  ), false );
} );

When calling the namespace "/wp-json/watz/v1" I get a correct response in Postman that the route is shown.

However, when i try to access the route request directly, i get thrown a 404 error. So far I've tried:

  • Rewriting the permalinks
  • Using standard Wordpress .htaccess
  • Disabling plugins
  • Changing method/namespace & request
  • Testing other plugin routes like Yoast or Contact Form 7 (they work)

Any idea what could be causing the issue here and what I need to alter to get this working?

Share Improve this question asked Oct 8, 2019 at 12:17 BroodjeBEBroodjeBE 411 gold badge1 silver badge9 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 5

It's because of how you've defined the accepted methods:

'methods'   => '\WP_REST_Server::CREATABLE ',

You shouldn't have quotes around it. WP_REST_Server::CREATABLE is a string that equals 'POST', but by putting quotes around it you're literally setting the method as '\WP_REST_Server::CREATABLE', which is not a valid HTTP method. You can see this in the response to the namespace endpoint.

Set it like this:

'methods' => WP_REST_Server::CREATABLE

Or, if your file is using a PHP namespace, like this:

'methods' => \WP_REST_Server::CREATABLE

Or add this to the top of the file:

use WP_REST_Server;

Then make sure that when you're accessing the route directly, that you're using the correct method. If you're using WP_REST_Server::CREATABLE then the endpoint will only respond to POST requests, so GET requests will return a 404, which includes when you access it via the browser.

发布评论

评论列表(0)

  1. 暂无评论