我正在尝试使用 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}}
这是我用来制作 .GET 的 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 开发站点上都仍然存在。重新启动服务器和/或检查 this answer成功了。
最佳答案
工厂看起来不错,根据rest-api文档,您还需要漂亮的永久链接插件,以便rest-api插件使用自定义url重写 https://wordpress.org/plugins/rest-api/installation/
关于javascript - 使用 Angular.js 对 WordPress V2 API 进行基本 REST 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34959159/