Slim 框架:POST 始终为 null 的问题
Slim framework: POST always null issue
我正在尝试使用 Slim 开发身份验证 REST 服务。
用 GET 请求测试,一切正常。
但是,当我尝试将某些东西与 POST 一起使用时,似乎
$app->request()->post()
和
$app->request()->getBody()
始终为空。
我正在实现经典的 login() 函数,如下所示:
$app->post('/login', 'login');
function login() {
$app = \Slim\Slim::getInstance();
$response = array();
$post = json_decode($app->request()->getBody());
$response['post'] = $app->request()->post();
$sql = "SELECT * FROM utenti WHERE email = :email AND password = :password";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindParam("email", $post->email);
$stmt->bindParam("password", $post->password);
$user = $stmt->fetch(PDO::FETCH_OBJ);
$db = null;
$response['error'] = false;
$response['name'] = $user['name'];
} catch(PDOException $e) {
$response['error'] = true;
$response['mesage'] = $e->getMessage();
}
echoRespnse(200, $response);
}
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
// Http response code
$app->status($status_code);
// setting response content type to json
$app->contentType('application/json');
echo json_encode($response);
}
有什么建议吗?
你有两个选择。
application/json请求
将Content-Type
header设置为application/json
,将body中的数据发送为JSON:
{
"param1": "value1",
"param2": "value2"
}
并使用以下方式读取数据:
$response['post'] = json_decode($app->request()->getBody());
application/x-www-form-urlencoded请求
将Content-Type
header设置为application/x-www-form-urlencoded
,将body中的数据发送为key=value
:
param1=value1¶m2=value2
并使用以下方式读取数据:
$response['post'] = $app->request()->post();
我正在尝试使用 Slim 开发身份验证 REST 服务。 用 GET 请求测试,一切正常。 但是,当我尝试将某些东西与 POST 一起使用时,似乎
$app->request()->post()
和
$app->request()->getBody()
始终为空。
我正在实现经典的 login() 函数,如下所示:
$app->post('/login', 'login');
function login() {
$app = \Slim\Slim::getInstance();
$response = array();
$post = json_decode($app->request()->getBody());
$response['post'] = $app->request()->post();
$sql = "SELECT * FROM utenti WHERE email = :email AND password = :password";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindParam("email", $post->email);
$stmt->bindParam("password", $post->password);
$user = $stmt->fetch(PDO::FETCH_OBJ);
$db = null;
$response['error'] = false;
$response['name'] = $user['name'];
} catch(PDOException $e) {
$response['error'] = true;
$response['mesage'] = $e->getMessage();
}
echoRespnse(200, $response);
}
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
// Http response code
$app->status($status_code);
// setting response content type to json
$app->contentType('application/json');
echo json_encode($response);
}
有什么建议吗?
你有两个选择。
application/json请求
将Content-Type
header设置为application/json
,将body中的数据发送为JSON:
{
"param1": "value1",
"param2": "value2"
}
并使用以下方式读取数据:
$response['post'] = json_decode($app->request()->getBody());
application/x-www-form-urlencoded请求
将Content-Type
header设置为application/x-www-form-urlencoded
,将body中的数据发送为key=value
:
param1=value1¶m2=value2
并使用以下方式读取数据:
$response['post'] = $app->request()->post();