基本的REST调用WordPress V2 API与Angular.js

Basic REST calls to WordPress V2 API with Angular.js

本文关键字:API Angular js V2 WordPress REST 调用      更新时间:2023-09-26

我正在尝试在WordPress 4.4.1中使用新的V2 API和Angular进行基本查询。也许有人可以帮助我理解为什么 URL /wp-json/wp/v2/posts 给出带有 404 的 JSON 响应。

浏览到该 URL 会给我这样的 JSON:

{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}

这是我用来制作它的JavaScript。获取

var base    = 'http://localhost:8888/recruitler';
var posts   = '/wp-json/wp/v2/posts';
var user    = '/wp-json/wp/v2/users/'; // append user id
var s       = '/wp-json/wp/v2/posts?filter[s]='; // append search term
// basic HTTP call with Angular
var app = angular.module('app', ['ngRoute'])
app.factory('myService', function($http) {
    var myService = {
        async: function() {
          // $http returns a promise, which has a then function, which also returns a promise
          var promise = $http.get( base+posts ).then(function (response) {
            // The then function here is an opportunity to modify the response
            console.log(response);
            // The return value gets picked up by the then in the controller.
            return response.data;
          });
          // Return the promise to the controller
          return promise;
        }
    };
  return myService;
});
app.controller('MainCtrl', function( myService, $scope ) {
  // Call the async method and then do stuff with what is returned inside our own then function
    myService.async().then(function(d) {
        $scope.data = d;
    });
});

更新:这一定是局部环境问题。实时网站工作得很好。我已经测试过,这个问题在我所有本地的 WAMP 和 MAMP 开发站点上仍然存在。重新启动服务器并/或检查此答案使其正常工作。

工厂看起来是正确的,根据 rest-api 文档,您还需要漂亮的永久链接插件才能使用 rest-API 插件使用自定义 URL 重写 https://wordpress.org/plugins/rest-api/installation/