Using POST method returns forbidden 403 (WP-REST-API )

admin

Administrator
Staff member
I'm totally new to wordpress/php I'm trying to use Angular with the rest API to do basic CRUID on custom table
Code:
professor_schedule
.

To query the table everything works. This is what I have.

<strong>PHP</strong>

Code:
// get all schedules
function getAllProfessorSchedule( $data ) {
    global $wpdb;
    $query = "SELECT nom FROM `professor_schedule`";
    $list = $wpdb-&gt;get_results($query);
    return $list;
}
add_action( 'rest_api_init', function () {
    register_rest_route( 'professor-schedule/v2', '/all', array(
    'methods' =&gt; WP_REST_Server::READABLE,
    'callback' =&gt; 'getAllProfessorSchedule'
    ));
});

<strong>JS</strong>

Code:
function getAllSchedules(){
  $http({
    method: 'GET',
    url : 'http://localhost/structurecours/index.php/wp-json/professor-schedule/v2/all'

  }).then(function (response) {
          console.log(response.data)
          $scope.data = response.data
    }, function (response) {
      console.error("error !! ", response)
  });
}

Below is the code to insert data into the DB. The server respond with a <strong>403 (Forbidden)</strong>

I'm logged in with an administrator account I have tried with the <a href="https://github.com/WP-API/Basic-Auth" rel="nofollow noreferrer">Basic Auth plugin</a> but I always get the 403 error. I'm struggling for hours now.
I would get any advices. Thanks

<strong>PHP</strong>

Code:
function addNewSchedule( WP_REST_Request $request ) {
    // $args = array(
    //  'headers' =&gt; array(
    //      'Authorization' =&gt; 'Basic ' . base64_encode( 'user:password' ),
    //  ),
    // );
    // wp_remote_request( $url, $args );


    global $wpdb;
    $item = $request-&gt;get_json_params();

    $fields = array();
    $values = array();
    foreach($item as $key =&gt; $val) {
        array_push($fields, $key);
        array_push($values, $val);
    }
    $fields = implode(", ",$fields);
    $values = implode("','",$values);
    $query = "INSERT INTO `professor_schedule` (".$fields.") VALUES ('".$values."')";
    //$query = "INSERT INTO `professor_schedule` ('Nom') VALUES ('test')";
    $list = $wpdb-&gt;get_results($query);

    return $list;
}


add_action( 'rest_api_init', function () {
  register_rest_route( 'professor-schedule/v2', '/add', array(
    'methods' =&gt; WP_REST_Server::CREATABLE,
    'callback' =&gt; 'addNewSchedule',
    'permission_callback' =&gt; function () {
      return current_user_can( 'edit_others_posts' );
    }
  ) );
} );

<strong>JS</strong>

Code:
$scope.addNewSchedule = function(){

  $http({
      method : "POST",
      url : "http://localhost/structurecours/index.php/wp-json/professor-schedule/v2/add",
      params:
      {
          nom : $scope.scheduleModel.nom
      }
  }).then(function(){
    getAllSchedules();
  });
}