简体   繁体   中英

React Native - How to get private posts from WordPress REST API using JWT Token

I have done logging-in WordPress Rest API with JWT Plugin passing administrator account and password and stores the received token in AsyncStorage like this.

await AsyncStorage.setItem(
    'user',
    JSON.stringify({
      token: userData.token,
      user_email: userData.user_email,
      user_nicename: userData.user_nicename,
      user_display_name: userData.user_display_name,
    }),
  );

Then I manage to get all posts including private post by including the token with request header like this,

  let userInfo = await AsyncStorage.getItem('user');
  let jsonUser = await JSON.parse(userInfo);
 
  let credential = 'Bearer ' + jsonUser.token;
  
  fetch('http://localhost/reactnativewordpress/wp-json/wp/v2/posts', {
    headers: {
      Authorization: credential,
    },
    method: 'GET',
    withCredentials: true,
    credentials: 'include',
  })
    .then(response => response.json())
    .then(responseJson => {
      
      this.setState({
        items: responseJson
        
      });
    })
    .catch(error => {
      
      console.log('Error :' + error);
      
    });

The responseJson have only public posts, no private post at all.

Thanks for help.

You need to add the

status=private

in your request,

like this http://localhost:8000/wp-json/wp/v2/posts?status=private

With that, the Authorization header should run;)

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