使用 Angular 5 将 POST 数据发送到 php

RJ_*_*J_7 2 php rest web-services angular angular5

我正在尝试从 Angular 5 调用 Web 服务到 PHP。

我正在使用 POST 方法,但在 PHP 端检索数据时遇到问题。

发送数据显示在有效负载中,但不会在 php 端检索。

角度服务.ts

this.URL = "http://localhost/angular/WEBSERVICE_PHP/test.php";

const headers = new Headers();
headers.append('Content-Type', 'application/json');
let data = 'visitor_id=55';

return this.http
.post(this.URL,JSON.stringify(data),{
    headers: headers
})
.map( Response => console.log(Response) );
Run Code Online (Sandbox Code Playgroud)

PHP页面

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET");
header('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies
header('content-type: text/plain');  
header("content-type: application/x-www-form-urlencoded");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X- 
Requested-With");
header("Access-Control-Max-Age: 172800");

if(isset($_POST))
{
    // $post = 'test data';     // This data get sent
    //   return $post;
    echo $post = $_POST['visitor_id'];
    return $post; 
}
Run Code Online (Sandbox Code Playgroud)

del*_*8uk 5

当“发布”JSON 时,您不会看到$_POST.

相反,这样做:

$json = file_get_contents('php://input');
$array = json_decode($json, true);
Run Code Online (Sandbox Code Playgroud)

如果必须如此$_POST,您可以将 分配$array$_POST

另一个解决方案是从 Angular 端开始,而不是发送 JSON 字符串,而是发送正确的帖子!(我不是 Angular 人,也许有人可以发表评论,我会添加代码!)