dongyaxiao5884 2019-03-10 15:07
浏览 308

POST请求没有正确到达httpClient - ionic - php

I'm creating a REST API in PHP. The service login is:

<?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;
?>

And as you may see, I'm accessing $_POST global variable.

  • Postman: sending a POST request with header x-www-form-urlenconded and specifying the keys and values, the server does capture such keys.
  • Ionic: sending a POST request using HttpClient will not work. (The server captures null for both keys, username and password).

This is the code of the provider:

  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);
  }

I'm wondering how the body should be formatted, and according to this link should be like I have done (username=user&password=pass). By the way, all parameters are not null when the login function is called, hence, the problem is in the request.

For those of you interested, the answer of the server is:

{message: "Unauthorized", username: null, success: false}

Any help will be appreciated.

  • 写回答

1条回答 默认 最新

  • duanlang1531 2019-03-10 16:14
    关注

    I'm copying my comment as an answer 'cause I want to post a photo.

    Assuming you're using Angular's HttpClient, try to specify which type you're sending via POST: try to do something as this.http.post<string>(url, 'string', opts);.

    I also suggest you to take a look at what you're sending as request via Chrome's Inspector (<kbd>F12</kbd> on windows/linux, <kbd>Cmd</kbd>+<kbd>Options</kbd>+<kbd>I</kbd> on Mac), Network tab.

    Obviously you must open it before sending request to be captured by DevTools. If you're debugging directly through the phone, on Windows/Linux you can use Remote Devices tab on Chrome's DevTools, or Safari on Mac.

    An example using Chrome's DevTools:

    评论

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号