Http POST doesn't work

I have created the login & signup function with Ionic 2.
I used the http module of Angular 2 to create.
But I got that Error Message:

EXCEPTION: Unexpected end of JSON input

The code as following:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import 'rxjs/add/operator/map';

  selector: 'page-home',
  templateUrl: 'home.html'
export class HomePage {

  log: string;

  login: {username?: string, password?: string} = {};

  constructor(public navCtrl: NavController, public http: Http) { }

    let data = JSON.stringify({
      username: this.login.username,
      password: this.login.password

    let url = 'http://.../api/login/';

    let headers = new Headers({
      'Content-Type': 'application/json'

    let options = new RequestOptions({
      headers: headers
    });, data, options).map(res => 
                 res.json()                                 //    this is the error
    ).subscribe(_data => {

      if(_data.result == true){
        this.log = _data;

The user click login button, it execute the loginUser function.
I tested the backend with postman and it’s fine.
I have been removed map function, then the error message disappeared but I can’t get any result.

I can get the response when I test with postman
The response is here.


And the server side script code is following.

   include_once ('../config.php');

    $username = '';
    $password = '';

    $username = $_POST['username'];
    $password = md5($_POST['password']);

    if (isset($username) && isset($password)){
        $qry="SELECT * FROM user_management WHERE username = '".$username."' AND password = '".$password."'";
        //echo $qry;
        $res = mysqli_query($conn, $qry);
            $arr =array('result' => true,
                        'userid' => $row['id'],
                        'username' => $row['username'],
                        'email' => $row['email']
            $arr =array('result' => false);

        echo json_encode($arr);

How can I fix that?

A couple of things:

  • there’s no need to call JSON.stringify on POST payloads. you can just pass objects.

  • if you’re testing this on iOS, all http POSTs will semi-silently fail as blank. you must use https.

1 Like
 return new Promise(resolve => {, data, options)  
        .map(res => res.json())
        .subscribe(data => {
      },(err) => {
          //Nothing found
          //Do something if no data is send back like a Alert "Login Failed"
          //Or Do:

I don’t understand why this promise creation antipattern is so persistent. What are you possibly gaining here?

1 Like