如何解决Vite Vue向Symfony后端传递变量失败问题
问题:Vite Vue前端发送JSON变量,Symfony控制器无法接收
已通过nelmioCorsBundle解决跨域问题,Firefox控制台显示变量发送格式正常,但Symfony控制器始终接收不到请求体中的JSON数据。
前端代码(view01.vue)
<script setup lang='ts'> import { ref } from 'vue' const message = ref('') fetch("/api") .then(response => response.json()) .then(data => { message.value = JSON.stringify(data); }); const V01 = ref("Please enter value to send to Symfony"); function onSubmit() { const obj = { value: V01.value }; console.log(JSON.stringify(obj)); fetch('https://localhost:8000/api/receive/data/php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(obj) }) .then(response => { // 原代码无响应处理,建议添加日志排查 }) .catch(error => { console.log(error) }); } </script> <template> <main> <section class="section01"> {{ message }} <br> <form @submit.prevent="onSubmit"> <label for="inputField">Please enter value to send to Symfony</label> <br> <input type="text" id="inputField" v-model="V01" /> <br> <button type="submit">ENTER</button> </form> </section> </main> </template> <style scoped> .section01 { width: 800px; height: 400px; background-color: green; padding: 50px; border: 6px solid #000000; } </style>
Symfony控制器代码(ReceiveDataPhpController.php)
<?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class ReceiveDataPhpController extends AbstractController { #[Route('/api/receive/data/php', name: 'app_receive_data_php')] public function index(Request $request): Response { $jsonObject = $request->getContent(); echo "The controller code is being executed<br>"; var_dump($jsonObject); echo "Length of JSON object: " . strlen($jsonObject) . "<br>"; if($jsonObject) { echo "<br>tt bon"; } else { echo "pas tt bon"; } echo "<br>"; $data = json_decode($jsonObject, true); if (json_last_error() !== JSON_ERROR_NONE) { $errorMsg = json_last_error_msg(); echo "Error decoding JSON data: " . $errorMsg . "<br>"; } var_dump($data); echo "<br>"; if ($data === null) { return new Response('The JSON data is invalid'); } if (isset($data['value'])) { $value = $data['value']; return $this->render('receive_data_php/index.html.twig', [ 'controller_name' => 'ReceiveDataPhpController', 'value' => $value, ]); } else { return new Response('The value element is not set in the JSON data'); } } }
截图说明
- Firefox控制台:可见发送的JSON字符串格式正确(如
{"value":"测试内容"}),请求无报错 - Symfony控制器输出:
$jsonObject为空字符串,长度为0,进入pas tt bon分支,json_decode返回null,最终返回The JSON data is invalid
解决方案
1. 显式指定路由请求方法
在路由注解中添加methods: ['POST'],确保只接受POST请求,避免方法不匹配的问题:
#[Route('/api/receive/data/php', name: 'app_receive_data_php', methods: ['POST'])]
2. 使用Symfony内置JSON解析方法(推荐)
Symfony 5.1+提供$request->toArray()方法,可直接将JSON请求体解析为数组,自动处理解析错误,替代手动的getContent()和json_decode:
修改控制器核心逻辑:
public function index(Request $request): Response { try { $data = $request->toArray(); } catch (\Symfony\Component\HttpKernel\Exception\BadRequestHttpException $e) { return new Response('Invalid JSON data', Response::HTTP_BAD_REQUEST); } if (isset($data['value'])) { $value = $data['value']; return $this->render('receive_data_php/index.html.twig', [ 'controller_name' => 'ReceiveDataPhpController', 'value' => $value, ]); } else { return new Response('The value element is not set in the JSON data', Response::HTTP_BAD_REQUEST); } }
3. 完善前端响应日志排查
在前端fetch的then中添加日志,确认后端返回的具体内容,定位问题:
.then(response => { console.log('响应状态:', response.status); return response.text(); }) .then(responseText => { console.log('响应内容:', responseText); })
4. 检查Symfony配置
确保config/packages/framework.yaml中没有干扰请求解析的配置:
framework: http_method_override: false # 避免覆盖POST方法
内容的提问来源于stack exchange,提问作者redrabbit
相关产品推荐
相关产品推荐

