簡體   English   中英

如何使用Angular 4進行發布請求?

[英]How to make a post request with Angular 4?

我正在嘗試使用此代碼向Angular 4發出發布請求,以發送lat和lng參數:

let data = {lat: this.newLat, lng: this.newLng};

this.http.post(url, data)
  .map(response => response.json())
  .subscribe(getResponse => console.log(getResponse));

在服務器端,我有以下php代碼段:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");

if ( isset($_POST['lat'], $_POST['lng']) ) {
    $response['msg'] = 'ok';
} else {
    $response['msg'] = 'not ok';
}
echo json_encode($response);

不幸的是,服務器的響應始終是'not ok' 任何想法如何解決這個問題? $_POST變量始終是一個空數組

請參閱說明文件

如果請求配置對象的data屬性包含一個對象,則將其序列化為JSON格式。

$ httpProvider.defaults.headers.post:(POST請求的標頭默認值)Content-Type:application / json


Angular將數據編碼為JSON,而不是PHP將自動解析為$_POST的數據格式之一。

您需要按照此答案中的說明解析JSON

PHP超全局$_POST僅應包裝application/x-www-form-urlencodedmultipart/form-data-encoded

但是,如果請求的Content-Type是其他任何內容。 您需要使用:

$post = file_get_contents('php://input');

有關更多信息,請參見以下答案: https : //stackoverflow.com/a/8893792/2394254

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM