How to post json object with Http.post (Angular 2) (php server side)

此生再无相见时 提交于 2019-11-29 14:45:31

angular 2 client side part

 ngOnInit() { 

        let body=Api+'product.php'+'?id=' + this.link_id;
        this._callservice.callregister(body)
                    .subscribe( data => {
                                this.outputs=data;                           
                       }, 
                    error => console.log("Error HTTP Post"),
                    () => console.log("completed") );  
      }    
    }

call.service.ts

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

@Injectable()
export class AuthenticationService {

  constructor(private _http:Http){}

  postregister(api:any){
//      console.log(api);
  let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
  let options = new RequestOptions({ headers: headers, method: "post"});
      return this._http.get(api,options)
          .map(res => res.json())
          .catch(this.handleError);
  }
  private handleError (error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || ' error');
    }

}

Server side PHP make sure on server side you have these three lines in php code.

   header('Access-Control-Allow-Origin: *');    
    header('Access-Control-Allow-Headers: X-Requested-With');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

Php file:

  <?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
$servername = "localhost";
$username1 = "root";
$password = "root";
$dbname = "product";

$e=array("error"=>1,"message"=>"Account Already Exists");

$accountCreated = array( "error" =>0, 
                         "data" => array(
                                   "username" => "amit" , 
                                   "password" => "anypassword",
                                   "role"=> "user", 
                                   "id" => "anyid" ) );

// Create connection
$conn = mysqli_connect($servername, $username1, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

    $username = $_GET["username"];
    $Pass = $_GET["password"];
    $role= $_GET["role"];
    $sql="SELECT COUNT(*) as user FROM users WHERE username = '$username'";
    $result = mysqli_query($conn,$sql);
    $line = mysqli_fetch_assoc($result);
    $count = $line['user'];
    if($count!=0)
       {
          echo json_encode($e);
       }
    else
       {
         $sql="INSERT INTO users(username,password,role)VALUES('$username','$Pass','$role')";
         $result=mysqli_query($conn,$sql);
         $sql="select * from users where username ='$username'";
         $result=mysqli_query($conn,$sql);
         $line=mysqli_fetch_assoc($result);
         {
             $accountCreated['data']['username']=$line['username'];
             $accountCreated['data']['password']=$line['password'];
             $accountCreated['data']['role']=$line['role'];
             $accountCreated['data']['id']=$line['id'];
         }
         echo json_encode($accountCreated);
        }

 ?>

i hope this will work for you .. for json i guess you should pass as options and use json decode for values you get in options.

There doesn't appear to be anything wrong with the Angular code. The issue is in what the PHP is expecting to receive. I am not a PHP expert, but as you've mentioned that it works fine with jQuery, then that indicates that your PHP is expecting a URL-encoded value (as jQuery tends to work with that), not a JSON value.

In other words, what the server is trying to parse is:

search=person

What you are sending is:

{ "search": "person" }

Try something more like the following to send it in the format you're wanting:

let test_this = { "search": "person" };
let headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers, method: "post" });

http.post(this.post_url, test_this, options)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!