WP REST API v2 and Angular $http POST request

I am trying to add a comment to my WordPress blog with WP-REST API v2 and AngularJS’s http. With GET requests everything works properly.

If I use the POST request this way (adding the parameters to the URL) everything works properly and the comment is added with the data.

Read More
$http({
  method: 'POST',
  url: 'http://myblog.com/json/wp-json/wp/v2/comments?author_name=Myself&content=Hello guys',
  headers: {
    'Content-Type': undefined
  }
}).then(function (res) {
  console.info('[REST] POST request sent to "' + route + '"');
  d.resolve(res);
}, function (err) {
  console.error('[REST] POST request failed. Error message: ', err);
  d.reject(err);
});

But if I use it this way, with the “data” parameter for $http.get (according to the documentation), the comment is added to WordPress but it’s empty. Without content or name.

$http({
  method: 'POST',
  url: 'http://myblog.com/json/wp-json/wp/v2/comments',
  headers: {
    'Content-Type': undefined
  },
  data: {
    author_name: 'Myself',
    content: 'Hello guys'
  }
}).then(function (res) {
  console.info('[REST] POST request sent to "' + route + '"');
  d.resolve(res);
}, function (err) {
  console.error('[REST] POST request failed. Error message: ', err);
  d.reject(err);
});

Why does it not work the second way? Or should I do it with the parameters queried to the URL?

Regards.

Related posts

1 comment

  1. I solved it. I had to use the application/x-www-form-urlencoded Content-Type and use Angular’s $httpParamSerializerJQLike on the data.

    $http({
      method: 'POST',
      url: self.address + route,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: $httpParamSerializerJQLike(params)
    }).then(function (res) {
      console.info('[REST] POST request sent to "' + route + '"');
      d.resolve(res);
    }, function (err) {
      console.error('[REST] POST request failed. Error message: ', err);
      d.reject(err);
    });
    

Comments are closed.