2017-10-10 57 views
0

角4.4.4
的HttpClient無法發送的數據這是我的應用程序組件角4點POST

constructor(
    private http: HttpClient, 
) 

this.http.post('/api.php', {name, age}).subscribe(data => { 
    console.log(data); 
}); 

api.php -> exit(json_encode($_POST));

沒有收到$ _ POST

返回任何數據[] ;

let xmlRequest = new XMLHttpRequest(); .... 正常工作)

我嘗試設置頭

let headers = new HttpHeaders().set('Content-Type', 'application/json; charset=UTF-8'); 

不行

對不起,這個問題,但我花了1天,還是沒找到解。

ps。客戶端和服務器有相同的來源。

+0

收到請發表你的PHP方法 –

+0

出口(json_encode($ _ POST)) –

+0

我的意思,您的簽名,您的方法完全 –

回答

0

我找到了解決這個。

在PHP中,$_POST只接受formdata。

隨着請求頭 '內容類型:應用程序/ JSON' 你可以用file_get_contents('php://input');

所以

$_POST = json_decode(file_get_contents('php://input')); 
1

請嘗試,我希望它會幫助你

import { Injectable } from '@angular/core'; 
import { Observable } from 'rxjs'; 
import 'rxjs/add/operator/map'; 
import { HttpClient } from '@angular/common/http'; 


@Injectable() 
export class LandingService { 

    private apiUrl = 'http://localhost:5000/'; 

    list:any; 
    headers : any; 
    constructor(private _http: HttpClient){ 
     this.headers = new Headers(); 
     this.headers.append('Content-Type', 'application/json'); 
    } 
    getsearchResponse(searchText){ 
      this.list ={"sentences":searchText} 
      return this._http.post(this.apiUrl+'searchBotsNew',this.list,this.headers) 
      .map(res =>res.json()) 
      .do(data => console.log(JSON.stringify(data))); 

     } 



} 
+0

謝謝。但我想嘗試新的HttpClient –

+0

有你在app.module.ts文件中導入HttpClientModule? –

+0

是的,我做到了。請求發送但服務器不recive數據 –