1

I am trying to authenticate the user logging in ,but my data is not getting into server ,so I am getting failed even if I enter the correct email and password

This is my component,

import { Component } from '@angular/core';
import { Router, ROUTER_DIRECTIVES } from '@angular/router';
import { CORE_DIRECTIVES, FORM_DIRECTIVES } from '@angular/common';
import { Http, Headers } from '@angular/http';
import { contentHeaders } from '../headers/headers';
  @Component({

directives: [ ROUTER_DIRECTIVES, CORE_DIRECTIVES, FORM_DIRECTIVES ],
 templateUrl : "./components/login/login.html",

   })
  export class Login {
    constructor(public router: Router, public http: Http) {
  }

  login(event, email, phone) {
   event.preventDefault();
   let body = JSON.stringify({ email, phone });
   var headers = new Headers();


   this.http.post('http://localhost/angular/index.php/profile/logIn',   body, {headers:headers})
  .subscribe(
    response => {
        if(response.json().error_code ==0){
             localStorage.setItem('social_id', response.json().id);
      this.router.navigate(['/demo/profile']);
     // console.log(body);
       alert('hi');
        }
        else{
     alert('fail');
        }
    },
    error => {
      alert(error.text());
      console.log(error.text());
      }
    );
   }
 }

My template,

 <div class="login jumbotron center-block">
  <h1>Login</h1>
  <form role="form" (submit)="login($event, email.value, phone.value)">
  <div class="form-group">
   <label for="username">Username</label>
    <input type="text" #email class="form-control" id="emailh" placeholder="Username">
  </div>
 <div class="form-group">
   <label for="password">Password</label>
    <input type="password" #phone class="form-control" id="phoneh" placeholder="Password">
 </div>
 <button type="submit" class="btn btn-default">Submit</button>
   <a [routerLink]="['/signup']">Click here to Signup</a>

I think I have gone wrong at headers and I don't have idea about it can someone point out where the error is......

My server code(codeigniter)

<?php
header("Access-Control-Allow-Origin: *");

defined('BASEPATH') OR exit('No direct script access allowed');

class Profile extends CI_Controller
{
    public function index()
    {
        $this->load->view('welcome_message');
    }

    public function logIn()
    {

        $email = $this->input->post('email');
        $phone = $this->input->post('phone');
        $this->load->model("Profile_Model");
        $res = $this->Profile_Model->logIn($email, $phone);
        if ($res) {
            $message               = array();
            $message['error_code'] = 0;
            $message['message']    = 'success';
            $message['data']       = $res;
            echo json_encode($message);
            exit;

        } else {
            $message               = array();
            $message['error_code'] = 1;
            $message['message']    = 'fail';
            $message['data']       = new stdClass;
            echo json_encode($message);
            exit;
        }

    }
}
Dario
  • 3,905
  • 2
  • 13
  • 27
MMR
  • 2,869
  • 13
  • 56
  • 110
  • What does your console or your network inspector tell you about your request using developer tools? I smell the cors issue here. – malifa Jun 29 '16 at 12:40
  • What ever i enter in login form the console says fails,therefore my data is not entering to server and may the problem is with sending data to server – MMR Jun 29 '16 at 12:43

1 Answers1

1

I think that you missed to set the Content-Type header in your code:

let body = JSON.stringify({ email, phone });
var headers = new Headers();
headers.append('Content-Type', 'application/json');

this.http.post('http://localhost/angular/index.php/profile/logIn',  
    { email, phone }, { headers })
    (...)

You can notice that from RC2, the header can be set implicitly based on what is provided as input. For example application/json for a JSON object, as described below:

this.http.post('http://localhost/angular/index.php/profile/logIn',  
    { email, phone })
    (...)
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • hi Thierry,it syas the following error "XMLHttpRequest cannot load http://localhost/angular/index.php/profile/logIn. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response." – MMR Jun 29 '16 at 12:48
  • But the definition is `post(url: string, body: any, options?: RequestOptionsArgs): Observable;` So im wondering how this works. Doesn't it expect `let headers = new Headers({ 'Content-Type': 'application/json' });` and then `let options = new RequestOptions({ headers: headers });` and using this `options` in your `post()` instead? – malifa Jun 29 '16 at 12:48
  • @nlr_p you should read up about `CORS`. It's a server issue in your case, not an angular / client issue. – malifa Jun 29 '16 at 12:50
  • @lexith,can u plesae paste the link – MMR Jun 29 '16 at 12:51
  • 1
    You have to allow `cross origin requests` on your backend. How you do that depends on your server. What are you using? Apache with PHP, IIS, Node? – malifa Jun 29 '16 at 12:53
  • @nlr_p this link could interest you: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/. In short, with POST requests, an OPTIONS request is sent before the target request. This request must contain a `Access-Control-Allow-Headers` header in its request with the `Content-Type` header or * specified in its value... – Thierry Templier Jun 29 '16 at 12:54
  • @lexith yes you're right, there was a typo in my answer. I fixed this. Thanks very much for pointing this out ;-) – Thierry Templier Jun 29 '16 at 12:55
  • you're welcome @ThierryTemplier but still (without trying!) i guess you get a compiler error there, because `post` explicitely expects an instance of `RequestOptions`, not just `any` like you did there with `{ headers }`. But well this has nothing to do with the OPs question. Just wondering :) – malifa Jun 29 '16 at 12:59
  • @nlr_p I think that you need to add something ;-) This link could help you: https://remysharp.com/2011/04/21/getting-cors-working. – Thierry Templier Jun 29 '16 at 13:04
  • @nlr_p your code doesn't matter at this point. What you want to do is set the correct `headers`. This depends on your framework, WHEN to do that. So just google `cors codeigniter` and you probably find thousands of posts. Another searchterm could be `php set headers to allow cors`. First match: http://stackoverflow.com/questions/8719276/cors-with-php-headers (One hint: many forget that you have to allow not just `Get, Post` but also `Options` which is important for the `POST preflight`. And Take a look at the link Thierry provided some comments ago. Seems pretty solid what he wrote there ;) – malifa Jun 29 '16 at 13:04
  • @lexith the last parameter is of type `RequestOptionsArgs`. An `headers` entry can be used. See https://angular.io/docs/ts/latest/api/http/index/RequestOptionsArgs-interface.html and https://angular.io/docs/ts/latest/api/http/index/Http-class.html#!#post-anchor – Thierry Templier Jun 29 '16 at 13:05
  • arrrr ;) thanks for pointing this out. I have the `interfaces.d.ts` open and looking at it. im a blind fool. – malifa Jun 29 '16 at 13:06
  • when i enter the user details(correct or wrong) in form it is returning else{ $message = array(); $message['error_code'] = 1; $message['message'] = 'fail'; $message['data'] = new stdClass; echo json_encode($message);exit; } – MMR Jun 29 '16 at 13:13