【问题标题】:Send Data from Angular Application to API through HTTP POST通过 HTTP POST 将数据从 Angular 应用程序发送到 API
【发布时间】:2018-02-22 14:53:56
【问题描述】:

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

错误:

1:在 data.service.ts 中带有 httpOptions 参数 -> http post 方法

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

3:网络

我不明白为什么在添加 Content-Type 标头时出现“405 不允许的方法错误”:application/json(错误 1)。如果我删除它,错误不会出现,但没有数据到达 API(错误 2)。

Content Type Header 在 API 的 php 文件中设置。 php文件中也允许POST方法。

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

json x-www-form-urlencoded

我做错了什么?

  • 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 表单

<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>

【问题讨论】:

    标签: php angular typescript


    【解决方案1】:

    你试过了吗?

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

    来自:Reading JSON POST using PHP

    【讨论】:

    • 谢谢。这就是解决方案。它在 post 方法中没有 httpOptions 的情况下工作。
    • 我修改了我的 API,以便它可以处理选项请求。现在它与 httpOptions 一起工作。谢谢你们两个的帮助:)
    【解决方案2】:

    尝试修改这个,你错过了S for OPTIONS 方法,并添加HEAD 方法:

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

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

    【讨论】:

    • 我仍然得到第二个错误。如果我再次在服务 http post 方法中添加 httpOption,我仍然会收到第一个错误
    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 2012-08-04
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多