Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php POST请求中的Symfony正文表单数据为空_Php_Rest_Symfony_Web_Postman - Fatal编程技术网

Php POST请求中的Symfony正文表单数据为空

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

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

我使用了表单数据选项

<?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