【问题标题】:Basic REST calls to WordPress V2 API with Angular.js使用 Angular.js 对 WordPress V2 API 的基本 REST 调用
【发布时间】:2016-01-23 03:07:15
【问题描述】:

我正在尝试使用 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 使其正常工作。

【问题讨论】:

    标签: javascript angularjs wordpress get


    【解决方案1】:

    工厂看起来不错,根据 rest-api 文档,您还需要漂亮的永久链接插件,以便 rest-api 插件使用自定义 url 重写 https://wordpress.org/plugins/rest-api/installation/

    【讨论】:

    • 哦,哇,你也需要那个插件吗? API有点乱吧?现在我收到GET http://localhost:8888/recruitler/wp-json/wp/v2/posts net::ERR_EMPTY_RESPONSE
    • 尝试使用 127.0.0.1 而不是 localhost
    • 我一直在玩 URL 并研究了 4 个小时......我不知道如何使用 API。
    • 我刚刚在我的笔记本电脑上安装了 wordpress,我启用了数字永久链接并添加了来自 codex.wordpress.org/htaccess 的示例 .htaccess(我使用了子文件夹示例)。如果您将 wp 安装在子文件夹中,那么您将更改 RewriteBase 值。在我的 .htaccess 中,它看起来像这样: RewriteBase /wordpress/
    猜你喜欢
    • 2017-06-16
    • 1970-01-01
    • 2018-02-17
    • 2017-11-28
    • 2019-11-23
    • 1970-01-01
    • 2018-01-09
    • 2015-05-20
    • 2014-12-23
    相关资源
    最近更新 更多