首页 > 解决方案 > 端点无法使用 SLIM 框架在 PHP 中正确发出 POST 请求

问题描述

我正在尝试使用遵循本教程的 SLIM 框架创建一个应该连接到数据库的 API 服务器。实际上我做了一个端点,它从数据库中获取数据,但不能插入新的。

每次我尝试插入新数据时,POST 参数都是空值,并且数据库只发送一条错误消息。

在我的 groupes.php 中,我有以下内容:

<?php

use Slim\Http\Request;
use Slim\Http\Response;

// Routes

$app->get('/[{name}]', function (Request $request, Response $response, array$args) {
   // Sample log message
   $this->logger->info("Slim-Skeleton '/' route");

   // Render index view
   return $this->renderer->render($response, 'index.phtml', $args);
});

$app->group('/api', function () use ($app) {

   $app->group('/v1', function () use ($app) {
       $app->get('/clients', 'getClients');
       $app->post('/make', 'addClient');
   });
});

上面的代码只是定义了两个端点:getClientsaddClient

在我的 index.php 中,我有:

function getConnection(){
    $dbhost = "127.0.0.1";
    $dbuser = "root";
    $dbpass = "dzpga883yRusPHhv";
    $dbname = "pruebaandroid";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
}

//method: GET
//domain: mi-api/api/v1/clients
function getClients($response){
    $sql = "SELECT * FROM cliente";
    try{
        $stmt = getConnection()->query($sql);
        $client = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;

        return json_encode($client);
    } 

    catch(PDOException $e){
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

//method: POST
//domain: mi-api/api/v1/make
function addClient($request) {
    $client = json_decode($request->getBody());

    $sql = 'INSERT INTO cliente (nombre, apellido, cedula, direccion, telefono, email) VALUES (:nombre, :apellido, :cedula, :direccion, :telefono, :email)';

    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam(":nombre", $client->nombre);
        $stmt->bindParam(":apellido", $client->apellido);
        $stmt->bindParam(":cedula", $client->cedula);
        $stmt->bindParam(":direccion", $client->direccion);
        $stmt->bindParam(":telefono", $client->telefono);
        $stmt->bindParam(":email", $client->email);
        $stmt->execute();
        $client->id = $db->lastInsertId();
        $db = null;
        echo json_encode($client);
    } 

    catch(PDOException $e){
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

因此,使用邮递员执行 GET 请求以mi-api/api/v1/clientes检索指定的所有数据,但是当我尝试使用 POST 请求mi-api/api/v1/make?nombre=asdf&apellido=asdf&cedula=asdf&direccion=asdf&telefono=asdf&email=asdf时,它应该插入新信息,但邮递员给了我以下错误:

{"error":{"text":SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'nombre' cannot be null}}

看起来addClient它没有获取参数的函数,所以它把它当作空。为什么会这样?我不知道这里有什么问题,欢迎任何回复。

看图片 在此处输入图像描述

PD:是的,数据库格式正确,它有一个作为 PK 自动增量的 id,我尝试打印echo client->nombre,只打印错误。

标签: phppostgetrequestslim

解决方案


您正在将参数添加为GET参数(在 url 上添加)。

使用 BODY -> form-data 选项卡指定POST参数(与 PARAMS 选项卡中的参数相同)

在此处输入图像描述


推荐阅读