Unable to query data using HTTP POST but it works with GET

30 views
Skip to first unread message

Dawg

unread,
Oct 25, 2016, 2:35:20 PM10/25/16
to Angular
Hello,

Not sure what I'm doing wrong but I can't seem to send an http post request but I am able to use the get to retrieve the information. I like to know what it is that I'm doing wrong in this instance?

Any help you can provide would be greatly appreciated.

My service.ts file

import { Injectable } from '@angular/core';
import { Headers, Http, Response, URLSearchParams, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { PersonType } from '../services/persontype';

@Injectable()
export class UserLoginService{
    userLoginInformation: PersonType[];

    constructor(private _http: Http){  }

    userAuthenticationMethod(uInfo: any): Observable<any[]>{
       let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); 
       let options = new RequestOptions({ headers: headers });
      
       let params: URLSearchParams = new URLSearchParams();
       params.set('userName', uInfo.userName);// test name

        // return this._http 
        //     .get(this.userUrl, {search: params})
        //     .map((res: Response) => res.json())
        //     .catch(this.handleError);  

        return this._http 
            .post(this.userUrl, {search: params}, options)
            .map((res: Response) => res.json())
            .catch(this.handleError);           
    }//END - userAuthenticationMethod

   private handleError(error: any) {
    console.error('An error occurred1', error); // for demo purposes only
    return Observable.throw(error.message || error);
  }
}//END class



The PHP file that access the database

<?php
header("Access-Control-Allow-Origin: *");
include('dbhandler.php');
$dbcon = Connection::getConnection();
//$newSearch = $_GET['userName'];
$newSearch = $_POST['userName'];

try {
$STMT = $dbcon ->query("SELECT * from tbl_users WHERE userName = '$newSearch' ");
$userListOutput = $STMT->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e){
echo 'DB error: ' . $e->getMessage(); 
}
 echo json_encode($userListOutput); 
?>




Sander Elias

unread,
Oct 31, 2016, 12:58:10 AM10/31/16
to Angular
Hi Dawg,

header("Access-Control-Allow-Origin: *") Allows only simple-requests(bassicly get) on CORS. To be able to use any of the other methods on http your CORS configuration needs to be set properly. (anything outside simple-requests needs more config on the server side!)

Here is an article on how to do a better php cors implementation.

Regards
Sander
Reply all
Reply to author
Forward
0 new messages