我正在进行登录身份验证,无法识别故障。通过AJAX,我将用户名和密码传递给login.php,后者调用PHP REST API来验证凭据并使用包含帐户状态的JSON进行响应,并将消息推送回UI。
我正在使用file_get_contents
调用api。 apiURL是localhost / api / v1 / login。
的login.php
$data = array('username' => $username, 'password' => $password);
$options = ["http" =>
["method" => "POST",
"header" => "Content-Type: application/json",
"content" => json_encode($data)
]
];
// Call API
$apiResponse = json_decode(file_get_contents($apiUrl, NULL, stream_context_create($options)));
问题似乎是我的api电话,但我无法弄清楚问题是什么。
API
$response = array("status" => "active", "message" => "success");
header('Content-Type: application/json');
echo json_encode($response);
我使用postman chrome扩展程序测试我的API并发送和接收JSON而没有问题,因此API代码正常运行。如果我在login.php中执行var_dump($apiResponse)
,则从API返回的值为NULL。
关于为什么这个值为NULL的任何想法?我是否错误地调用了api端点?
答案 0 :(得分:0)
$data = http_build_query(
array('username' => $username, 'password' => $password)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $data
)
);
$apiResponse = json_decode(file_get_contents($apiUrl, false, stream_context_create($opts)));
这可能对你有所帮助,但我还没有测试过代码
参考:php,stackoverflow