AJAX请求FOSUser创建用户

时间:2017-06-17 07:47:00

标签: javascript ajax symfony

为了测试FOSUser,我正在模拟一个AJAX请求,该请求发送包含用户名,电子邮件和密码的JSON数据。

JavaScript方面(远非完美的ajax请求,但我会在实际开发中使用Angular):

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:未捕获PHP异常   Symfony \ Component \ Debug \ Exception \ ContextErrorException:“注意:   试图获得非对象的属性“at   C:\ wamp64 \ WWW \ MyWebsite \ SRC \的appbundle \控制器\ DefaultCont roller.php   第50行{“例外”:“[对象]   (Symfony的\元器件\调试\异常\ ContextErrorException(代码:   0):注意:尝试获取非对象的属性   C:\ wamp64 \ WWW \ MyWebsite \ SRC \的appbundle \控制器\德发ultController.php:50)“}   []“那是:if(!$ userManager-&gt; findUserByUsername($ data-&gt; userna

有什么想法吗? :)

1 个答案:

答案 0 :(得分:0)

好的,我是个傻瓜。 $ data什么都没有;我必须使用$ request-&gt; getContent()...

public function createUserAction(Request $request, UserManager $userManager)
    {
        $data = json_decode($request->getContent());

感谢大家的评论:)