Symfony body form-data null in a POST request



最近我一直在尝试制作一个Symfony应用程序,但是我在向Body发出POST请求时遇到了问题。

邮递员请求如下所示

我为它使用了表单数据选项

<?php
namespace AppController;
use AppEntityUser;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationRequest;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentHttpFoundationResponse;
use PsrLogLoggerInterface;
class UserController extends AbstractController
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @Route("/user", name="addUser", methods={"POST"})
*/
public function addUser(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$this->logger->info("hi");
$this->logger->info(json_encode($request));
$username = $data["username"];
$password = $data["password"];
if (empty($username) || empty($password)) {
throw new NotFoundHttpException('Expecting mandatory parameters!');
}
$this->accountRepository->saveAccount($username, $password );
$response = new JsonResponse(['status' => 'Account created!'], 201);
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
}

但是可变$request是空的

{"属性":{},"请求":{},"查询":{},"服务器":{},"文件":{},"cookies":{}

,"headers":{}}

显然,由于此,代码遇到了错误

如果发送 JSON,请不要使用formData而是将原始模式与Content-type: application/json header一起使用。

如果您需要使用formData,请使用Symfony表单进行使用$form->handleRequest($request)

最新更新