【问题标题】:Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()Slim、Postman 和 AngularJs:$app->request->getBody() 与 $app->request->post()
【发布时间】:2016-09-01 14:38:38
【问题描述】:

我是初学者。我编写了一个测试应用程序,由客户端的 AngularJs GUI 和服务器端的 PHP API 组成。

这是处理请求的角度服务

myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){

    return $resource(API_URL + '/books/:bookId', {bookId: '@bookId'}, {
        get: { method: 'GET', isArray:true },
        update: { method: 'PUT'},
        save: { method: 'POST'},
        delete: {method:'DELETE'},
    });

}]);

当我从 Angular 应用程序提交一本书时,我可以使用 Slim 捕捉 POST

$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty

当我使用 Postman 并执行 POST 时,我可以使用

在 Slim 中捕获 POST
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();

我不明白为什么会有这种差异。你能解释一下吗?

我不是打算只用 $app->request->post();在这两种情况下?为什么来自 Angular 的帖子只能用 $app->request->getBody() 捕获?

【问题讨论】:

    标签: angularjs rest slim postman


    【解决方案1】:

    $app->request->post() 方法检索在application/x-www-form-urlencoded 请求中提交的键/值数据。如果请求使用不同的内容类型(例如application/json),您可以使用$app->request->getBody() 方法检索原始请求正文并根据需要对其进行解码。如果您还有其他问题,请告诉我。

    【讨论】:

    • 哈!我明白了,谢谢!我的观点也是要了解如何使用 Postman 测试端点,现在我看到我必须将 Header Content-Type 设置为“application/json”,然后正文必须是“Raw”并且必须包含类似的 json {"title":"new title"} 一切正常。
    【解决方案2】:

    你仍然可以使用

    $post_b = $app->request->post()

    在苗条中。

    只要您通过将数据作为格式化的表单值而不是 JSON 传递来从 html 表单 (AngularJS) 调用此 REST 服务。 如果在 AngularJS 中你有 JSON 格式的数据,你必须先把它翻译成形式。下面是如何调用此 REST 服务的示例:

    Object.toparams = function ObjecttoParams(obj) {
        var p = [];
        for (var key in obj) {
            p.push(key + '=' + encodeURIComponent(obj[key]));
        }
        return p.join('&');
    };
    
    $http({
        method: 'POST',
        url: url,
        data: Object.toparams(myobject),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })

    myobject 是要创建的 JSON 格式的数据

    【讨论】:

      【解决方案3】:

      谢谢 Josh..您的回答对我有用。

      要遵循的步骤:

      1.您需要在原始选项卡下以json格式发送请求,如下所示:

      {"username":"admin","password":"admin"}
      

      2.您需要在标题中将Content-Type设置为application/json

      就是这样,它会起作用的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-12
        • 1970-01-01
        • 2020-10-15
        • 2018-03-08
        • 2019-10-27
        • 2021-04-27
        • 1970-01-01
        • 2016-01-28
        相关资源
        最近更新 更多