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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制