我在Symfony3中有一个函数,它将数据发布到mysql数据库。该函数如下所示:
/**
* @Route("/LegoPieces")
* @METHOD("POST")
* @View()
*
* @Annotations\QueryParam(
* name="piece", nullable=false, description="piece"
* )
* @Annotations\QueryParam(
* name="type", nullable=false, description="type"
* )
* @Annotations\QueryParam(
* name="startDate", nullable=false, description="Start Date YYYY-MM-DD HH:MM:SS (Should be in the future)"
* )
* @Annotations\QueryParam(
* name="endDate", nullable=false, description="End Date YYYY-MM-DD HH:MM:SS (Should be no more than 3 weeks in the future)"
* )
*/
public function postAction(ParamFetcherInterface $paramFetcher)
{
$piece = $paramFetcher->get('piece');
$type = $paramFetcher->get('type');
$start = $paramFetcher->get('startDate');
$end = $paramFetcher->get('endDate');
$startDate = DateTime::createFromFormat('Y-m-d H:i:s', $start);
$endDate = DateTime::createFromFormat(' Y-m-d H:i:s', $end);
$em = $this->getDoctrine()->getManager('default');
$data = new LegoPieces();
$data->setPiece($piece);
$data->setType($type);
$data->setStartDate($startDate);
$data->setEndDate($endDate);
$em->persist($data);
$em->flush();
return new JsonResponse("LegoPieces Added Successfully", 200);
}
当我用字符串替换变量($ piece,$ type,$ startDate,$ endDate)时,post请求有效。但是,当我尝试通过像Postman或javascript之类的东西发布帖子请求时:
fetch("http://localhost:8000/LegoPieces", {
method: "POST",
body: {
startDate: this.startDate,
endDate: this.endDate,
piece: this.piece,
type: this.type
}
}).then(response => response.json())
);
});
我收到500错误!我不明白 - 谢谢你的帮助!
查看您的日志,您的错误是什么。
但你必须改进你的控制器!您不使用Symfony表单,也没有任何验证。即使您现在没有500错误,如果您不尊重您的实体类型,将来也会有一些错误。
我也不明白为什么你使用帖子请求并且不传递你体内的所有参数。您只在网址中使用get参数。
不知道什么异常使那500 - 你什么都不知道:(
试着看看响应体
没有这些信息 - 我只有一个想法。
如果您在开发环境中工作,那么您的js请求可能根本看不到路由(以及其他内容)
清除缓存文件夹的所有内容
rm -rf var/cache/*
和
php bin/console c:w -e prod