WP REST API v2 和 Angular $http POST 请求

WP REST API v2 and Angular $http POST request

我正在尝试使用 WP-REST API v2 和 AngularJS 的 http 向我的 WordPress 博客添加评论。使用 GET 请求一切正常。

如果我以这种方式使用 POST 请求(将参数添加到 URL),一切正常,并且评论会与数据一起添加。

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

但是如果我以这种方式使用它,使用 $http.get 的 "data" 参数(根据文档),评论将添加到 WordPress,但它是空的。没有内容或名称。

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

为什么第二种方式不行?或者我应该使用查询到 URL?

的参数来执行此操作

此致。

我解决了。我必须使用 application/x-www-form-urlencoded Content-Type 并在数据上使用 Angular 的 $httpParamSerializerJQLike

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