【问题标题】:POST request does not arrive properly httpClient - ionic - phpPOST 请求未正确到达 httpClient - ionic - php
【发布时间】: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 请求将不起作用。 (服务器为 usernamepassword 这两个键捕获 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&lt;string&gt;(url, 'string', opts);。我还建议您通过 Chrome 的 Inspector(Windows/Linux 上的 F12,Mac 上的 Cmd+Options+I)、标签网络查看您作为请求发送的内容。显然,您必须在发送请求以被 DevTools 捕获之前打开它。如果你直接通过手机调试,在 Windows/Linux 上你可以使用 tab Remote Devices,在 Mac 上你可以使用 Safari
  • 我正在使用httpClient。奇怪的是,通过将此"username="+user+"&amp;password="+pass 设置为body,服务器会捕获username 而不是password。关于 chrome 开发工具中的网络选项卡,我只能看到响应,但看不到查询。谢谢

标签: php api httpclient ionic4


【解决方案1】:

我复制我的评论作为答案,因为我想发布一张照片。

假设您使用的是 Angular 的 HttpClient,请尝试指定您通过 POST 发送的类型:尝试使用 this.http.post&lt;string&gt;(url, 'string', opts);

我还建议您通过 Chrome 的 Inspector 查看您发送的请求(在 windows/linux 上为 F12Cmd+Options+I 在 Mac 上),网络选项卡。

显然你必须在发送请求之前打开它才能被 DevTools 捕获。如果您直接通过手机进行调试,在 Windows/Linux 上,您可以使用 Chrome 的 DevTools 上的 Remote Devices 选项卡,或 Mac 上的 Safari。

使用 Chrome 的 DevTools 的示例:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多