0

I'm seeing this in the Chrome browser console after doing a test fetch request:

Access to fetch at 'http://localhost/wptest2/wp-json/pluginFolder/1.0/load?limit=10&offset=0' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

But in my plugin entry file I have this. Note the order:

function add_cors_http_header($served) {
  header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: X-WP-Nonce", false);

  return $served;
}
add_filter('rest_pre_serve_request', __NAMESPACE__ . '\\' . 'add_cors_http_header');

// this registers the /load route
add_action('rest_api_init', [$apiController, 'registerLoadCouponRoute']);

Any idea why I'm getting the error when it appears I have the header set?

In case you want to see the route handler and callback, or the fetch request, I am including both below:

// ApiController.php     
public function loadCoupons(\WP_REST_Request $request) {
    global $wpdb;

    $queryParams = $request->get_params();

    $userDetails = get_current_user();

    // 2 queries removed

    wp_send_json([
      'rows' => $rows
      , 'totalCount' => $totalCount
    ]);
  }

  public function registerLoadCouponRoute() : void {
    register_rest_route($this->namepaceAndVersion, "load", [
      'methods' => ['get', 'post'],
      'callback' => [$this, 'loadCoupons']
    ]);
  }


// fetch request made inside a React.js useEffect:
const fetchSomeCoupons = async (limit = 10, offset, jwt = null) => {
    try {
      const response = await fetch(
        // `${apiBaseUrl}${namepaceAndVersion}/load?limit=${limit}&offset=${offset}`
        `http://localhost/wptest2/wp-json/pluginFolder/1.0/load?limit=10&offset=${offset}`
        , {
        method : 'get'
        , headers : {
          'X-WP-Nonce' : clientNonce
          , 'Authorization' : `Bearer ${jwt}`
        }
      });
      let data = await response.json();

      if (data && 'error' in data) {
        setSnackbarMessage(data.error)
      }

      return data;
    }
    catch (e) {
      // console.log(e, `=====error=====`);
      throw e;
    }
  };


  /** ON INITIAL LOAD AND CHANGES TO PAGE OFFSET
   *
   * Sets up couponData state, which also controls whether a table or "Nothing to Display" message is shown
   *
   * Also sets pagination state for the offset and total record count
   */
  useEffect( () => {
    fetchSomeCoupons(10, pageOffset, jwt)
      .then(data => {
          if (_.isEqual(data.rows, couponData) === false) {
            setCouponData(data.rows);
            setTotalRecordCount(data.totalCount);
          }
      })
      .catch(e => console.log(e, '====error===='));
  }, [pageOffset]);

Edit: I should also note there was no header issue with this request:

    <button
      onClick={async () => {
        console.log(jwt, `=====jwt=====`);

        const x = await fetch('http://localhost/wptest2/wp-json/jwt-auth/v1/token/validate', {
          method : 'post'
          , mode : 'cors'
          , headers : {
            'Content-Type' : 'application/json'
            , 'Authorization' : `Bearer ${jwt}`
          }
        });

        const json = await x.json();
        console.log(json, `=====json=====`);
        return json;
      }}
    >test jwt auth</button>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.