DEV Community

Cover image for Integrate WordPress rest Api in Reactjs
MOHSIN ALI SOOMRO
MOHSIN ALI SOOMRO

Posted on

Integrate WordPress rest Api in Reactjs

Hi There Hope you are fine
Demo here

I will integrate rest API in react js using JWT authentication for that you need a plugin to install in your WordPress and active it.
JWT Auth — WordPress JSON Web Token Authentication.
WordPress JSON Web Token Authentication allows you to do REST API authentication via a token. It is simple, non-complex, and easy to use. This plugin probably is the most convenient way to do JWT Authentication in WordPress.
by useful team

The react app is integrated with wp rest API and crud operation on the posts
steps

1: Open the .htaccess file in the root folder of WordPress and paste

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
Enter fullscreen mode Exit fullscreen mode

2: Open the wp-config.php file in the root folder of WordPress and paste

get the secret key from the given link or you put your own
link

define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
define('JWT_AUTH_CORS_ENABLE', true);
Enter fullscreen mode Exit fullscreen mode

Now you get endpoint for authentication
http://yourdomain.com/wp-json/jwt-auth/v1/token

Using axios

Promise based HTTP client for the browser and node.js

const loginData = {
            username: "Username",
            password: "Password"
        };
axios.post('http://yourdomain/wp-json/jwt-auth/v1/token', loginData)
    .then((res) => {
        console.log(res.data);
        localStorage.setItem('token', res.data.token);
        localStorage.setItem('user_nicename', res.data.user_nicename);
        localStorage.setItem('user_email', res.data.user_email);
        localStorage.setItem('user_display_name', res.data.user_display_name);
    })
    .catch((err) => {
        console.log(err);
    });
Enter fullscreen mode Exit fullscreen mode

Crud Operation Endpoint for posts

Get All post (get all post you does not need any token)
http://yourdomain.com/wp-json/wp/v2/posts

axios.get('http://yourdomain/wp-json/wp/v2/posts')
    .then((res) => {
        console.log(res.data)   
    })
    .catch((err) => {
        console.log(err);
});
Enter fullscreen mode Exit fullscreen mode

Create a post (You need an authentication token from login)
http://yourdomain.com/wp-json/wp/v2/posts

const formdata = {
    title: title,
    content: content,
    status: 'publish'
};

axios.post('http://yourdomain/wp-json/wp/v2/posts', formdata, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
    })
    .then((res) => {
        console.log(res);           
    })
    .catch((err) => {
        console.log(err)
});
Enter fullscreen mode Exit fullscreen mode

Edit Post (You need an authentication token from login)
http://yourdomain.com/wp-json/wp/v2/posts/id

const formdata = {
    title: title,
    content: content,
    status: 'publish'
};
axios.post('http://yourdomain/wp-json/wp/v2/posts/'+id, formdata, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
    })
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log(res);
});
Enter fullscreen mode Exit fullscreen mode

Delete Post (You need authentication token from login)
http://yourdomain.com/wp-json/wp/v2/posts/id

axios.delete('http://yourdomain/wp-json/wp/v2/posts/' + id, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
    })
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log(err);
});
Enter fullscreen mode Exit fullscreen mode

For code here is the GitHub link
code

If there is any difficulty feel free to comment I will reply to you asap

Thanks for ready if this will helpful for you then comments and star my repo

Discussion (6)

Collapse
ivicaha profile image
ivica-ha

Hey,
I can't seem to go pass COARSE. Alwas the same error. Not sure what can I update.
I've set all the .htacces and config lines, but I always get:

Access to XMLHttpRequest at 'localhost:8080/wp-json/jwt-auth/v1...' from origin 'localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any ideas? Maybe http?

Thanks for the help in advance.
Regards,

Collapse
mohsinalisoomro profile image
MOHSIN ALI SOOMRO Author • Edited on

Thanks for comment here, can you send me screenshot of the exact error you get.
Here is the GitHub repo that may help you github.com/MohsinAliSoomro/wp-rest...

Collapse
dance2die profile image
Sung M. Kim

Hi there Mohsin.

Would you format the code snippets?
You could check out the editor guide for documentation :)

Collapse
mohsinalisoomro profile image
MOHSIN ALI SOOMRO Author

Thank you Sung M. Kim for providing the documentation guidelines

Collapse
dance2die profile image
Sung M. Kim

yw and thank you for taking time to making it better~

Collapse
lailahgrant profile image
lailahgrant

Thanks for the post, meanwhile, im tring to access your finished application but can't go beyond login