私は最初のAPIを作成しています。スリムなPHPを使用することを選択しました。これまでのところ、私は必要なものの基礎をする素晴らしい軽量フレームワークだと思います。私が本当に持っていた唯一の問題は、私のルートの応答が正しいステータスコードを返さないことでした。私は成功したログインで200を返し、失敗したログインで403を間違った資格で返します。私が返すのは、それが何を返しても200です。正しいJSONが返されていることがわかるため、ロジックが動作しています。ステータスコードは変更されません。Slim PHP正しいステータスコードが返されない
のindex.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App;
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->withHeader('Access-Control-Allow-Origin', 'http://mysite')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});
require_once 'api/login.php';
$app->run();
Login.php
$app->post('/api/login', function ($request, $response){
require_once 'db.php';
$q = "SELECT * FROM blog_admin WHERE username = ? AND password = ?";
$stmt = $mysqli->prepare($q);
$stmt->bind_param('ss', $user, $pass);
$user = $request->getParsedBody()['username'];
$pass = md5($request->getParsedBody()['password']);
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows > 0){
$token = md5(uniqid($user, true));
date_default_timezone_set("America/Toronto");
$logged_in = date('Y/m/d');
$data = array(
"flash" => 'success',
"message" => '<strong>SUCCESS:</strong> You have entered the correct login information! Please wait while you are redirected...',
'_token' => $token,
'logged_in' => $logged_in
);
$q = "UPDATE blog_admin SET _token=?, last_logged_in=?";
$stmt = $mysqli->prepare($q);
$stmt->bind_param('ss', $token, $logged_in);
if($stmt->execute()){
$response->withJson($data, 200);
}else{
$data = array(
"flash" => 'danger',
"message" => '<strong>ERROR:</strong> Could not login! Please try again later!'
);
$response->withJson($data, 403);
}
}else{
$data = array(
"flash" => 'danger',
"message" => '<strong>ERROR:</strong> The Username/Password you have entered is incorrect. Please try again.'
);
$response->withJson($data, 403);
}
}else{
$data = array(
"flash" => 'danger',
"message" => '<strong>ERROR:</strong> Could Not Run the SQL'
);
$response->withJson($data, 500);
}
return $response;
});
私は問題が何であるかわからないので、任意のアイデアは非常に理解されるであろう。