如何使用Http.post(Angular 2)发布json对象(php服务器端)

时间:2016-12-15 00:03:35

标签: php json angular typescript angular2-http

我试图重新创建Post JSON from angular 2 to php,但它没有工作,因为php端的$_REQUEST变量中没有任何内容

代码:

searchHttp({body}: any): Promise<any>
{   
    let headers = new Headers ({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, method: "post" });

    let test_this = {"search": "person"};

    return this.http.post(this.post_url, JSON.stringify(test_this), options)
        .toPromise()
        .then(response =>  
            {   
                return response.text();
            })  
        .catch(this.handleError);
}

我有什么遗失的东西吗?我知道帖子可以使用其他格式,因为我已经在另一个问题中回答了这个问题。

此外,http.request优于http.post吗?

编辑:

经过Angular / Javascript专家的多次咨询后,他们认为这是一个php问题。所以任何知道如何在php端接受JSON对象的人都会受到欢迎。

2 个答案:

答案 0 :(得分:4)

角度2客户端部分

 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');
    }

}

服务器端PHP 确保在服务器端你在PHP代码中有这三行。

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

Php文件:

  <?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);
        }

 ?>

我希望这对你有用..对于json我猜你应该传递选项并使用json解码来获得你在选项中获得的值。

答案 1 :(得分:1)

Angular代码似乎没有任何问题。问题在于PHP期望收到的内容。我不是PHP专家,但正如你所提到的,它适用于jQuery,那表明你的PHP期望一个URL编码的值(因为jQuery倾向于使用它),而不是JSON值。

换句话说,服务器试图解析的是:

search=person

您发送的内容是:

{ "search": "person" }

尝试更多类似下面的内容,以您想要的格式发送它:

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)