Reputation: 4747
I'm trying to figure out how to use Node.js WPAPI with a Wordpress blog hosted on Wordpress.com.
You probably know that Wordpress.com sites don’t have the typical /wp-json
endpoint; instead you can find the Wordpress.com JSON REST API on https://public-api.wordpress.com/wp/v2/sites/MYSITE.wordpress.com
, e.g. https://public-api.wordpress.com/wp/v2/sites/amazingstartupguide.wordpress.com
I’m using WPAPI for Node.js version 2.0.0-alpha.1
and the promise-based v2 syntax used in the WPAPI docs:
import WPAPI from 'wpapi'
const siteSlug = 'amazingstartupguide'
const siteUrl = `https://public-api.wordpress.com/wp/v2/sites/${siteSlug}.wordpress.com`
const wp = new WPAPI({ endpoint: siteUrl })
console.log('wp:', wp);
console.log('await wp.posts().get():', await wp.posts().get())
The first console.log
outputs a WPAPI object that looks healthy, but when getting the posts
I get the error:
TypeError: this.transport.get is not a function
If I instead change the import to:
import WPAPI from 'wpapi/superagent'
I get:
Error: {
"code": "rest_no_route",
"message": "No route was found matching the URL and request method.",
"data": { "status": 404 }
}
What to do?
Upvotes: 1
Views: 705
Reputation: 6325
The WPAPI documentation states that to have access to the HTTP interaction methods (get
, post
, etc) you have to require it with:
const WPAPI = require('wpapi/superagent');
Once you do that, when you try to get the posts
you get indeed the error:
{
code: 'rest_no_route',
message: 'No route was found matching the URL and request method.',
data: { status: 404 }
}
This is a known issue with the library that seems to be reported in 2021 but still not fixed. Basically the library is requesting https://public-api.wordpress.com/wp/v2/sites/amazingstartupguide.wordpress.com/wp/v2/posts while the endpoint is https://public-api.wordpress.com/wp/v2/sites/amazingstartupguide.wordpress.com/posts (note that the library incorrectly adds a /wp/v2
before /posts
).
As stated in the issue, the best way to work around it would be:
const wp = new WPAPI({
endpoint: siteUrl
})
const posts = await wp.root('posts').get()
You would pass the relative API path via .root()
instead of being able to use the .posts()
method, etc.
Upvotes: 0
Reputation: 109
Using an alpha version of WPAPI (2.0.0-alpha.1) can be problematic due to incomplete features or bugs.Could you switch to a stable version and retry.
Upvotes: 0