通过HTTP POST将数据从Angular Application发送到API

时间:2018-02-22 14:53:57

标签: php angular typescript

我试图将我的angular 5 apllication中的单个对象发送到JSON格式的php API使用HTTP POST,但我无法让它工作。我知道这可能是非常基本的,但我是这个主题的新手,谷歌无法帮助我或我没有搜索正确的关键字。

错误:

1:使用data.service.ts中的httpOptions参数 - > http post方法 with httpOption

2:data.service.ts中没有httpOptions参数 - > http post方法 php文件中的第55行是这一行:$ name = $ _ POST [" name"];我也在文件中标记了它。 without httpOptions

3:网络 enter image description here

我不明白为什么我得到" 405不允许的方法错误"当我添加Content-Type标头:application / json(错误1)。如果我删除它,错误将不会显示,但没有数据到达API(错误2)。

内容类型标头在API的php文件中设置。在php文件中也允许使用POST方法。

我使用Restlet Client测试了API。它适用于Content-Type:application / x-www-form-urlencoded,但也不适用于application / json:

JSON enter image description here 的X WWW窗体-urlencoded enter image description here

我做错了什么?

  • Angular v5 - > package.json
  • Angularapp - >本地主机:4200
  • API - > localhost:81 Apache

data.service.ts - > full File

const httpOptions = { headers: new HttpHeaders({ 'Content-Type':'application/json' })};

...

saveName(name: Name) {
    const body = JSON.stringify(name.name);
    return this.http.post('http://localhost:81/apitest/src/app/data/name.php', body, httpOptions);
}

API

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTION");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

$connection = mysqli_connect('localhost', 'api', 'test', 'apitest');

$request_method = $_SERVER['REQUEST_METHOD'];

    switch($request_method){
    case 'GET':
        if(!empty($_GET['nameId'])){
            $nameId = intval($_GET['nameId']);
            getNames($nameId);
        } else {
            getNames();
        }
        break;
    case 'POST':
        insertNames();
        break;
    case 'PUT':
        updateNames();
        break;
    case 'DELETE':
        deleteNames();
        break;
    default:
        header('HTTP/1.0 405 Method Not Allowed');
        break;
}

function insertNames()
{
    global $connection;
    $name=$_POST["name"]; // LINE 55 | Undefined index: name in [...] on line <b>55</b><br />
    if(isset($_POST['name'])){
        $query="INSERT INTO form SET name='{$name}'";
        if(mysqli_query($connection, $query))
        {
            $response=array(
                'status' => 201,
                'status_message' =>'Name Added Successfully.'
            );
        }else
        {
            $response=array(
                'status' => 400,
                'status_message' =>'Name Addition Failed.'
            );
        }
    }
    else
    {
        $response=array(
            'status' => 400,
            'status_message' =>'Request Body Empty.'
        );
    }
    header('Content-Type: application/json');
    echo json_encode($response);

app.component.ts - &gt; full File

saveName() {
    this.dataService.saveName(this.name).subscribe(
        data => {
          this.getNames();
          return true;
        }, error => {
          console.error('Failed');
        }
    );
  }

HTML表单

<html>
<head>
  <title>API TEST</title>
</head>
<body>
  <form action="data/name.php" method="POST">
    <label for="name">Name: </label>
    <input type="text" name="name" [(ngModel)]="name.name">
    {{name.name}}
    <button name="post" (click)="saveName()">post</button>
  </form>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

你试过这个吗?

$json = file_get_contents('php://input');
$obj = json_decode($json, true);

$name = $obj['name']

来自:Reading JSON POST using PHP

答案 1 :(得分:2)

尝试修改此问题,您错过了S OPTIONS方法,并添加了HEAD方法:

header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, HEAD, OPTIONS");

当您调用CORS请求时,浏览器会将OPTIONS请求发送到服务器以了解允许哪些方法。这就是所谓的:Preflighted request