简体   繁体   中英

How to get JSON data from WP REST API

For a long time I've being working on how to get access to my WordPress posts. I'm using WP REST API plugin with the WP REST API - OAuth 1.0a Server, and I get an "401 - Only authenticated users can access the REST API" error.

I've read all the documentation and I touched the .htaccess , and I'm going crazy. Please someone help I don't know what to do, and I'm about to give up.

I tried add some code in the .htaccess file, and also tried AJAX and JavaScript fetch, and nothing seems to work. I know there are people using it. It'd be nice someone can tell me how to fix this, I really need it.

jQuery.ajax({
   url: 'http://laprensainsolita.com/wp-json/wp/v2/posts',
   method: 'GET',
   crossDomain: true,
   beforeSend: function ( xhr ) {
       xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 'username:password' ) );
   },
   success: function( data, txtStatus, xhr ) {
       console.log( data );
       console.log( xhr.status );
   }
});

Do I need to add any code to the .htaccess file? And if so what and where should I put it? Or what is need to make this work. I'm very desperate.

The error:

{
  "code": "rest_cannot_access",
  "message": "Only authenticated users can access the REST API.",
  "data": {
    "status": 401
  }
}

Please try to pass fields to store credentials. Add this fragment to your AJAX call

xhrFields: {
    withCredentials: true
},

Your call should look something like this:

Query.ajax({
 url: 'http://laprensainsolita.com/wp-json/wp/v2/posts',
 method: 'GET',
 crossDomain: true,
 xhrFields: {
    withCredentials: true
},
 beforeSend: function ( xhr ) {
   xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 
             'username:password' ) );
 },
   success: function( data, txtStatus, xhr ) {
   console.log( data );
   console.log( xhr.status );
 }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM