React REST API Post request

In order to post the data we need to verify the origin of the domain. In WordPress it’s quite normal to have the verify_nonce available, but in React we need to be able to access the nonce.

Below you can find the code for the post request.

POST with Axios

Make sure you have this libary included in your React project. And use the same headers here. The URL is your endpoint in WordPress. Headers must include the X-WP-Nounce and there the global variable is needed.

const whs_global = window.whs_global

    axios({
      method: 'post',
      headers: { 'X-WP-Nounce': whs_global.nonce },
      url:
        '/wp-json/xyz/v1/wholesale_register/',
      data: values,
    })
      .then((response) => {
        this.setState({ message: 'success' })
      })
      .catch((error) => {
        this.setState({ message: 'failure' })
      })

Localize script for React

Whenever you enqueue in the assets from the build file in React, you’ll need to localize the script with the nonce. This you can then access in React through the window global.

The nonce is needed to verify that this is an authorized request coming from the same domain.

I’ve added the full enqueue below.

<?php
defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );


add_action( 'init', function() {

    add_filter( 'script_loader_tag', function( $tag, $handle ) {
        if ( ! preg_match( '/^whs-/', $handle ) ) { return $tag; }
        return str_replace( ' src', ' async defer src', $tag );
    }, 10, 2 );

    add_action( 'wp_enqueue_scripts', function() {

        if(is_page_template( 'page-templates/wholesale-registration.php')) :

         

            $asset_manifest = json_decode( file_get_contents( WHS_ASSET_MANIFEST ), true )['files'];

            if ( isset( $asset_manifest[ 'main.css' ] ) ) {
                wp_enqueue_style( 'whs', get_site_url() . $asset_manifest[ 'main.css' ] );
            }

            wp_enqueue_script( 'whs-runtime', get_site_url() . $asset_manifest[ 'runtime-main.js' ], array(), null, true );

            wp_enqueue_script( 'whs-main', get_site_url() . $asset_manifest[ 'main.js' ], array('whs-runtime'), null, true );

            $data = array(
                'nonce' => wp_create_nonce('wp_rest'),
            );

            wp_localize_script('whs-main', 'whs_global', $data);

            foreach ( $asset_manifest as $key => $value ) {
                if ( preg_match( '@static/js/(.*)\.chunk\.js@', $key, $matches ) ) {
                    if ( $matches && is_array( $matches ) && count( $matches ) === 2 ) {
                        $name = "whs-" . preg_replace( '/[^A-Za-z0-9_]/', '-', $matches[1] );
                        wp_enqueue_script( $name, get_site_url() . $value, array( 'whs-main' ), null, true );
                    }
                }

                if ( preg_match( '@static/css/(.*)\.chunk\.css@', $key, $matches ) ) {
                    if ( $matches && is_array( $matches ) && count( $matches ) == 2 ) {
                        $name = "whs-" . preg_replace( '/[^A-Za-z0-9_]/', '-', $matches[1] );
                        wp_enqueue_style( $name, get_site_url() . $value, array( 'whs' ), null );
                    }
                }
            }

        endif;
    });
});

One comment

  1. […] interesting, since in React applications, you’ll need to access the nonce from somewhere. I’ve made an article about that as well as well as a longer tutorial with example […]

Leave a Reply