爲了測試FOSUser,我模擬了發送包含用戶名,他的電子郵件和密碼的JSON數據的AJAX請求。FOSUser創建用戶的AJAX請求
JavaScript端(遠從完美的Ajax請求,但我會在實際開發中使用角):
function ajaxPost(url, data, callback, isJson) {
let req = new XMLHttpRequest();
req.open("POST", url);
req.addEventListener("load", function() {
if (req.status >= 200 && req.status < 400) {
callback(req.responseText);
} else {
console.error(req.status + " " + req.statusText + " " + url);
}
});
req.addEventListener("error", function() {
console.error("Network error at " + url);
});
if (isJson) {
req.setRequestHeader("Content-Type", "application/json");
data = JSON.stringify(data);
}
req.send(data);
}
// Simulates an AJAX request to create a user from a form:
user = prompt("Username:");
email = prompt("Email:");
password = prompt("Password:");
data = { user, email, password };
ajaxPost("http://domain.tld/app_dev.php/createuser", data, console.log, true);
Symfony的一面:
/**
* @Route("/createuser", name="createUser")
*/
public function createUserAction($data, UserManager $userManager)
{
$data = json_decode($data);
if (!$userManager->findUserByUsername($data->username) && !$userManager->findUserByEmail($data->email)) {
$user = $userManager->createUser();
$user->setUsername($data->username);
$user->setEmail($data->email);
$password = password_hash($data->password, PASSWORD_DEFAULT);
$user->setPassword($password);
$userManager->updateUser($user);
return new Response("<html><body>New user created!</body></html>");
} else {
return new Response("<html><body>This user or email already exists.</body></html>");
}
}
當我直接去/ CREATEUSER並通過模擬數據,它的工作原理;但是當我發送我的ajax請求時,它始終返回500內部服務器錯誤:
[2017-06-17 08:31:49] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Debug\Exception\ContextErrorException: "Notice: Trying to get property of non-object" at C:\wamp64\www\MyWebsite\src\AppBundle\Controller\DefaultController.php line 50 {"exception":"[object] (Symfony\Component\Debug\Exception\ContextErrorException(code: 0): Notice: Trying to get property of non-object at C:\wamp64\www\MyWebsite\src\AppBundle\Controller\DefaultController.php:50)"} []" That's: if (!$userManager->findUserByUsername($data->userna
任何想法? :)
你能提供有關錯誤的一些信息?從日誌中提取它 – manuelbcd
我忘了看看它們...還不習慣Symfony:[2017-06-17 08:31:49] request.CRITICAL:未捕獲到PHP異常Symfony \ Component \ Debug \ Exception \ ContextErrorException :「注意:嘗試獲取非對象的屬性」在C:\ wamp64 \ www \ MyWebsite \ src \ AppBundle \ Controller \ DefaultController.php第50行{「exception」:「[object](Symfony \\ Component \\ Debug \\ Exception \\ ContextErrorException(code:0):注意:試圖在C:\\ wamp64 \\ www \\ MyWebsite \\ src \\ AppBundle \\ Controller \\ DefaultController.php中獲取非對象的屬性:在$ data = json_decode($ data)之後,如果(!$ userManager-> findUserByUsername($ data-> userna ... – Joubarbe
)可以執行dump($ data)'; '? – kRicha