Php POST请求中的Symfony正文表单数据为空
最近,我一直在尝试制作一个Symfony应用程序,但我在向一个机构发出POST请求时遇到了问题 我使用了表单数据选项Php POST请求中的Symfony正文表单数据为空,php,rest,symfony,web,postman,Php,Rest,Symfony,Web,Postman,最近,我一直在尝试制作一个Symfony应用程序,但我在向一个机构发出POST请求时遇到了问题 我使用了表单数据选项 <?php namespace App\Controller; use App\Entity\User; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Routing\Annotation\Route; use Symfony\Compon
<?php
namespace App\Controller;
use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Psr\Log\LoggerInterface;
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;
}
}
如果发送JSON,不要使用formData
,而是使用原始模式和内容类型:application/JSON header
如果您需要使用formData
,请使用Symfony表单$form->handleRequest($request)
,您的帖子是什么样子的?你能提供一个post请求的例子吗?你为什么在那里尝试使用json\u decode
?从你的邮递员截图上看,你一开始并不是在发送JSON。我一直在使用JSON\u decode
从请求中获取内容,也许这不是最好的解决方案。对于curl请求,我能提供的最好的解决方案是:非常感谢!我将raw与JSON一起使用,它工作正常我记得上次使用symfony时使用了formData