简体   繁体   中英

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.

$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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM