简体   繁体   English

如何为该RESTful实现发送$ http.delete()请求?

[英]How can I send a $http.delete() request for this RESTful implementation?

This is my PHP code. 这是我的PHP代码。

<?php

    header("Content-Type: application/json");
    // get the HTTP method, path and body of the request
    $method = $_SERVER['REQUEST_METHOD'];
    $request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
    var_dump($request);
    $input = json_decode(file_get_contents('php://input'),true);

    // connect to the mysqli database
    $link = mysqli_connect('localhost', 'root', 'hello', 'agita');
    mysqli_set_charset($link,'utf8');

    // retrieve the table and key from the path
    $table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
    $key = array_shift($request)+0;

    // escape the columns and values from the input object
    $columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
    $values = array_map(function ($value) use ($link) {
      if ($value===null) return null;
      return mysqli_real_escape_string($link,(string)$value);
    },array_values($input));

    // build the SET part of the SQL command
    $set = '';
    for ($i=0;$i<count($columns);$i++) {
      $set.=($i>0?',':'').'`'.$columns[$i].'`=';
      $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
    }

    // create SQL based on HTTP method
    switch ($method) {
      case 'GET':
        $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
      case 'PUT':
        $sql = "update `$table` set $set where id=$key"; break;
      case 'POST':
        $sql = "insert into `$table` set $set"; break;
      case 'DELETE':
        $sql = "delete `$table` where id=$key"; break;
    }

    // excecute SQL statement
    $result = mysqli_query($link,$sql);

    // die if SQL statement failed
    if (!$result) {
      http_response_code(404);
      die(mysqli_error());
    }

    // print results, insert id or affected row count
    if ($method == 'GET') {
      if (!$key) echo '[';
      for ($i=0;$i<mysqli_num_rows($result);$i++) {
        echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
      }
      if (!$key) echo ']';
    } elseif ($method == 'POST') {
      echo mysqli_insert_id($link);
    } else {
      echo mysqli_affected_rows($link);
    }

    // close mysqli connection
    mysqli_close($link);
?>

I have implemented a RESTful API, now I can receive the JSON object with the $http.get(url+customerId) . 我已经实现了RESTful API,现在可以使用$http.get(url+customerId)接收JSON对象。 This will return me the JSON object I want. 这将返回我想要的JSON对象。 Looking at the above server code what is the call I need to back for instance if I wanted to delete a customer with customerId 5? 查看上面的服务器代码,例如,如果要删除具有customerId 5的客户,我需要回叫什么?

I tried $http.delete(url+customerId).then() ... 我尝试了$http.delete(url+customerId).then() ...

But It does not seem to work. 但这似乎行不通。 Help needed. 需要帮助。

Take a look at the browser developer console to see what the script returns. 查看浏览器开发人员控制台以查看脚本返回的内容。 Since you say it returns a 500 I would assume that PHP crashes. 因为您说它返回500,所以我认为PHP崩溃了。 From what I see the mysqli_error misses the $link as parameter. 从我看到的mysqli_error错过了$link作为参数。 But the error log should contain a detail message. 但是错误日志应包含详细消息。

A few hints to your script: 您的脚本的一些提示:

  • I would use prepared statments instead of mysqli_real_escape_string 我将使用准备好的语句代替mysqli_real_escape_string
  • You could use the json_encode function to always return a proper JSON response. 您可以使用json_encode函数始终返回正确的JSON响应。 Ie maybe you can simply use: json_encode($result->fetch_all(MYSQLI_ASSOC)) to output the response on GET. 即,也许您可​​以简单地使用: json_encode($result->fetch_all(MYSQLI_ASSOC))在GET上输出响应。
  • I would return a 500 status code instead of 404 in case of an error 如果出现错误,我将返回500状态代码而不是404
  • You should use 404 only in case an entry does not exist $result->field_count == 0 仅在条目不存在的情况下才应使用404 $result->field_count == 0

Iam also the developer of Fusio an open source project which tries to simplfies building APIs like in your script. Iam还是Fusio的开发人员,Fusio是一个开放源代码项目,它试图简化在脚本中构建API的过程。 If you like you can check it out at: http://www.fusio-project.org/ 如果您愿意,可以在以下位置查看: http : //www.fusio-project.org/

I used the same script. 我使用了相同的脚本。

The problem here is this line of code: 这里的问题是这一行代码:

  case 'DELETE':
    $sql = "delete `$table` where id=$key"; break;

It needs to be updated to following code: 它需要更新为以下代码:

  case 'DELETE':
    $sql = "delete FROM `$table` where id=$key"; break;

Now run the code and it will work. 现在运行代码,它将起作用。 It worked for me. 它为我工作。

Here is the link to the actual code: 这是实际代码的链接:

https://www.leaseweb.com/labs/2015/10/creating-a-simple-rest-api-in-php/ https://www.leaseweb.com/labs/2015/10/creating-a-simple-rest-api-in-php/

Thanks, 谢谢,

Cherian. Cherian。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用带有AngularJS和Laravel的$ http.delete将数组传递给PHP? - How to pass an array to PHP using $http.delete with AngularJS and Laravel? 如何使用带有 PHP 后端的 Angular http.delete 从表中删除记录? - How to delete record from table using Angular http.delete with PHP backend? 在服务器上部署项目后,Angularjs http.delete无法正常工作 - Angularjs http.delete is not working after deploying project on server Angular - $ http.delete返回成功但不起作用 - Angular - $http.delete returns success but doesn't works RESTful:如何通过PUT和DELETE发送数据 - RESTful: how to send data through PUT and DELETE 如何将请求标头发送到Restful API - How to send Request Header to a Restful API 发送请求之前,如何查看我的HTTP或HTTPS请求? - How can I view my HTTP or HTTPS request before I send it? 如何使用php发送此GCM下游消息(HTTP POST请求)? - How can I send this GCM downstream message (HTTP POST REQUEST) using php? 我无法在Angular 4上将带有标头的http请求发送给laravel api - i can't send http request with header to laravel api on angular 4 php单击链接后,如何发送带有inc / decrease变量的http GET请求 - How can i send a http GET request with a variable that inc/decrease after link click with php
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM