Laravel用额外的''返回JSON响应`quote:" ' {"状态" 500"米

时间:2016-10-04 00:32:51

标签: php jquery json ajax

我使用jQuery $.ajax向我的Laravel 5.1 API发送ajax请求。

我试图简单地从服务器输出错误响应,但由于JSON.parse属性开头的流氓',我无法responseText响应值。

为什么那样?

enter image description here

前端

API.Auth.register(params).done(function (result) {

    // Do stuff

}).error(function (xhr, status, error) {
    console.log('Registration error: ', xhr);
    var parsed_response = JSON.parse(xhr.responseText);
    console.log('parsed_response', parsed_response);
    alertify.error('There was a problem with your registration.');
});

register : function (params)
{
    return $.ajax({
        url: globals.env.api_host + globals.env.api_ver + '/register',
        type: 'POST',
        data: params,
        dataType: 'json',
        cache: true
    })
},

Laravel 5.1 :我已尝试在" "中包装媒体资源,但错误结果相同:

public function register(Request $request)
{
    try {
        $new_user = $this->create($request->all());
    } catch (QueryException $e) {
        // error code 23000 is unique SQL unique constraint error - TODO: abstract this checking
        if ($e->getCode() === '23000') {
            return response()->json(['status' => 500, 'message' => 'This e-mail already exists. Try a new e-mail or logging in.']);
        } else {
            return response()->json(['status' => 500, 'message' => 'There was an error processing registration.']);
        }
    }

编辑:如果我只返回一个字符串,我测试'是否仍然存在:

    //Original Route:
    //$router->post('/register', 'Auth\AuthController@register');

    $router->post('/register', function () {
        return 'hello world';
    });

回复:'hello world

开头的单引号仍然存在。

旁注:我无法在jQuery ajax中捕获自定义异常消息。我首选的返回错误的方法是自定义例外:

throw new BadRequestHttpException('There was an error processing registration.');

但是$.ajax无法捕获异常消息,所以我已经从Laravel返回response()->json...

对此有何想法?

编辑:找到它。有人对config/app.php文件进行了意外更改,并添加了'。很奇怪Laravel如何通过仍然提供响应来对待它,但是在'之前。

enter image description here

1 个答案:

答案 0 :(得分:1)

经过大量搜索后,@ Derek建议我检查源控制是否存在诸如'单引号之类的流氓添加内容。

我发现有人意外地将'提交给config / app.php文件。

enter image description here

PHP将<php>标记之外的任何内容视为输出,因此它被“预先”添加到任何响应中。

这显然打破了JSON.parsing前端,因为响应有效负载格式错误的JSON。