【发布时间】:2019-03-10 15:07:22
【问题描述】:
我正在用 PHP 创建一个 REST API。服务login是:
<?php
include_once 'libs/Database.php';
header("Content-Type: application/json; charset=UTF-8");
Database::getPDO();
$myObj = null;
if ( Database::check($_POST['username'], $_POST['password']) ) {
$myObj = array('message' => "Verified", 'success' => true);
} else {
$myObj = array('message' => "Unauthorized", 'username' => $_POST['username'], 'success' => false);
}
$myJSON = json_encode($myObj);
echo $myJSON;
?>
如您所见,我正在访问$_POST 全局变量。
- 邮递员:发送带有标头
x-www-form-urlenconded的POST 请求并指定键和值,服务器会捕获这些键。 - Ionic:使用
HttpClient发送 POST 请求将不起作用。 (服务器为username和password这两个键捕获null。
这是提供者的代码:
login(user, pass, url) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
return this.http.post(url, "username="+user+"&"+"password="+pass, httpOptions);
}
我想知道body 应该如何格式化,并且根据this link 应该像我所做的那样(用户名=用户&密码=密码)。顺便说一句,调用login函数时所有参数都不为空,因此问题出在请求中。
对于那些感兴趣的人,服务器的答案是:
{message: "Unauthorized", username: null, success: false}
任何帮助将不胜感激。
【问题讨论】:
-
假设您使用的是 Angular 的 HttpClient,请尝试指定您通过 POST 发送的类型:尝试使用
this.http.post<string>(url, 'string', opts);。我还建议您通过 Chrome 的 Inspector(Windows/Linux 上的 F12,Mac 上的 Cmd+Options+I)、标签网络查看您作为请求发送的内容。显然,您必须在发送请求以被 DevTools 捕获之前打开它。如果你直接通过手机调试,在 Windows/Linux 上你可以使用 tab Remote Devices,在 Mac 上你可以使用 Safari -
我正在使用
httpClient。奇怪的是,通过将此"username="+user+"&password="+pass设置为body,服务器会捕获username而不是password。关于 chrome 开发工具中的网络选项卡,我只能看到响应,但看不到查询。谢谢
标签: php api httpclient ionic4