wpcom-xhr-request v1.2.0
wpcom-xhr-request
REST-API and WP-API requests via XMLHttpRequest (and CORS)
You likely want to use the high-level APIs in wpcom.js
instead of using this module directly.
Works in both the browser and Node.js via superagent.
Installation
Install wpcom-xhr-request using npm:
$ npm install wpcom-xhr-requestExample
<html>
<body>
<script src="wpcom-xhr-request.js"></script>
<script>
WPCOM.xhr('/me', function(err, data) {
if (err) throw err;
var div = document.createElement('div');
div.innerHTML = 'Your WordPress.com "username" is: <b>@' + data.username + '<\/b>';
document.body.appendChild(div);
});
</script>
</body>
</html>API
wpcomXhrRequest( params, fn )
Params: optional parameters
method:GETas default.apiNamespace:WP-APInamepsace.apiVersion:REST-APIapp version -1as default.proxyOrigin:https://public-api.wordpress.comas default.authToken: token authentication.query: object used to pass thequeryto the request.body: object used to pass thebodyto the request.form-data:POSTFormData (formultipart/form-data, usually a file upload).processResponseInEnvelopeMode: defaultTRUE.
fn: request callback function
This function has three parameters:
error: defined if the request failsbody: the object body of the responseheaders: the headers of the response
import handler from `wpcom-xhr-request`;
// get .com blog data usign `REST-API`
handler( '/sites/en.blog.wordpress.com', ( error, body, headers ) => {
if ( error ) {
return console.error( 'Request failed: ', error );
}
console.log( 'WordPress blog: ', body );
} );
// get .com blog data using `WP-API`
handler( {
path: '/sites/en.blog.wordpress.com',
apiNamespace: 'wp/v2'
}, ( error, body, headers ) => {
if ( error ) {
return console.error( 'Request failed: ', error );
}
console.log( 'WordPress blog: ', body );
} );
// get .org blog data (`WP-API`)
handler( {
proxyOrigin: 'http://myblog.org/wp-json',
path: '/',
apiNamespace: 'wp/v2'
}, ( error, body, headers ) => {
if ( error ) {
return console.error( 'Request failed: ', error );
}
console.log( 'WordPress blog: ', body );
} );Authentication
For API requests that require authentication to WordPress.com, you must pass in an
OAuth token as the authToken parameter in the params object for the API call.
You can get an OAuth token server-side through
node-wpcom-oauth, or any other OAuth2 interaction
mechanism.
Tests
make testmake test-watchLicense
MIT – Copyright Automattic 2014
5 years ago
7 years ago
7 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12 years ago
12 years ago