【发布时间】:2017-02-12 00:58:32
【问题描述】:
我正在使用 jQuery $.ajax 向我的 Laravel 5.1 API 发送 ajax 请求。
我试图简单地从服务器输出错误响应,但由于responseText 属性值开头的流氓' 导致无法JSON.parse 响应。
为什么会在那里?
前端:
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 仍然通过提供响应来处理这个问题,但在 ' 之前添加。
【问题讨论】:
-
检查状态文本的响应标头和 $.ajax 错误处理程序参数
-
@charlietfl laravel.com/docs/5.3/responses#json-responses 表示
response()->json(我正在使用)已经将标头类型设置为json。我检查了 ajax 响应中的状态文本,里面有那个流氓 ` ' ` 单引号。见上文 -
如果发送 400 或 500 系列状态码可以在 ajax 错误处理程序中得到响应消息
-
我还想指出,您不再需要
response()->json()- 返回数组将显示 json。 -
@Derek 谢谢 - 嗯。任何关于流氓
'单引号来自响应开头的任何想法:-->'<--{"status":"500","message":"There was an error processing registration."}