douqie3391 2018-02-22 14:53
浏览 251
已采纳

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

I am trying to send a single object from my angular 5 apllication to an php API in JSON format With HTTP POST, but i cant get it to work. I know this might be very basic but I am new to this topic and google cant help me or i am not searching the right keywords.

Errors:

1: With httpOptions parameter in data.service.ts -> http post method with httpOption

2: Without httpOptions parameter in data.service.ts -> http post method Line 55 in the php file is this one: $name=$_POST["name"]; I've also marked it in the file. without httpOptions

3: Network enter image description here

I do not understand why i get the "405 not allowed Method Error" when i add a the Content-Type Header: application/json (Error 1). If i remove it the error wont show up but no data arrives at the API (Error 2).

The Content Type Header is set in the php file of the API. POST Method along other is also allowed in the php file.

I tested the API with the Restlet Client. it worked with Content-Type: application/x-www-form-urlencoded but also not with application/json:

json enter image description here x-www-form-urlencoded enter image description here

What am I doing wrong?

  • Angular v5 -> package.json
  • Angularapp -> localhost: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 -> full File

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

HTML Form

<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条回答 默认 最新

  • doukun0888 2018-02-22 15:32
    关注

    did you try this?

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

    from: Reading JSON POST using PHP

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?