CakePHP 5 获取 POST 请求的正文数据

问题描述 投票:0回答:1

我正在使用 CakePHP 5 创建 REST API。我有一个 POST 函数,该函数应该从邮递员接收数据并将其输入到数据库。问题是我没有收到请求中的数据。 GET 请求运行良好,因此这绝对不是数据库问题。接收到的数据显示为空数组

[]
,其中 200 作为响应代码。谢谢您的宝贵时间。

routes.php

$routes->scope('/api', function (RouteBuilder $builder): void {
    $builder->connect('/product/insert', ['controller' => 'Product', 'action' => 'insertProduct'])->setMethods(['POST']);
});

ProductController.php

public function insertProduct() 
{
    $product = $this -> Product -> newEmptyEntity();
    $product = $this -> Product -> patchEntity($product, $this -> request -> getData());
    $this -> Product -> save($product);
}

我从框架文档中尝试过的其他事情:

$product_name = $this -> request -> getData('product_name');
$product = $this -> Product -> newEntity([
        'name' => $product_name,
]);

$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]);

$data = $this->request->getParsedBody();

$product = $this -> Product -> newEntity($this->request->getData());

debug($this->request);

我还有表和实体类:

产品表.php

namespace App\Model\Table;

use Cake\ORM\Table;

class ProductTable extends Table
{
      public function initialize(array $config): void
      {
           $this -> setTable('product');
           parent::initialize($config);
      }
}

产品.php

namespace App\Model\Entity;

use Cake\ORM\Entity;

class Product extends Entity
{

}

邮递员片段

php rest post cakephp postman
1个回答
0
投票

在 Postman 中将单选选项从“form-data”更改为“x-www-form-url-encoded”,您应该在 $_POST 中包含数据:

public function insertProduct()
{
    $this->request->allowMethod(['post']);

    $associations = [];
    $product = $this->Product->newEmptyEntity();
    // $this->Authorization->authorize($product); // Optional, if you use Authorization

    $data = $this->Product->sanitizeData($this->request->getData(), 'add', $this->authAdmin);
    $product = $this->Product->patchEntity($product, $data, ['associated' => $associations]);

    if ($this->Product->save($product)) {
        $this->set([
            'status' => 200,
            'message' => __('The product has been saved.'),
            'data' => $product,
        ]);
        $this->viewBuilder()->setOption('serialize', ['status', 'message', 'data']);
        return null;
    }

    $this->set([
        'status' => 400,
        'message' => __('The product could not be saved. Please try again.'),
        'errors' => $product->getErrors(),
    ]);
    $this->viewBuilder()->setOption('serialize', ['status', 'message', 'errors']);
    $this->setResponse($this->response->withStatus(400));
    return null;
}
© www.soinside.com 2019 - 2024. All rights reserved.