我只是Slim框架中的新手。我已经使用Slim框架编写了一个API。
来自iPhone应用程序的API发出了POST请求。此POST请求为JSON格式。
但是我无法访问iPhone请求中发送的POST参数。当我尝试打印POST参数的值时,每个参数都为“ null”。
$allPostVars = $application->request->post(); //Always I get null
然后,我尝试获取即将到来的请求的正文,将正文转换为JSON格式,然后将其发送回给iPhone。然后我得到了参数的值,但是它们的格式很奇怪,如下所示:
"{\"password\":\"admin123\",\"login\":\"[email protected]\",\"device_type\":\"iphone\",\"device_token\":\"785903860i5y1243i5\"}"
因此,可以肯定的是,POST请求参数即将到达此API文件。尽管它们在中不可访问$application->request->post()
,但它们已进入请求正文。
我的第一个问题是如何从请求正文访问这些POST参数,第二个问题是为什么在将请求正文转换为JSON格式后,请求数据为何显示为上述奇怪的格式?
以下是必要的代码段:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
$body = $application->request->getBody();
header("Content-Type: application/json");//setting header before sending the JSON response back to the iPhone
echo json_encode($new_body);// Converting the request body into JSON format and sending it as a response back to the iPhone. After execution of this step I'm getting the above weird format data as a response on iPhone.
die;
?>
通常,您可以通过以下POST
两种方式之一分别访问参数:
$paramValue = $application->request->params('paramName');
或者
$paramValue = $application->request->post('paramName');
文档中提供了更多信息:http : //docs.slimframework.com/#Request-Variables
当在中发送JSON时POST
,您必须从请求正文中访问信息,例如:
$app->post('/some/path', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true); // parse the JSON into an assoc. array
// do other tasks
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句