gpt4 book ai didi

php - 在 Laravel 中将 JSON 错误消息作为 "error"对象返回

转载 作者:行者123 更新时间:2023-12-01 04:00:27 24 4
gpt4 key购买 nike

我正在尝试使用 JQuery 的“Bootstrap File-input”插件,以便使用 AJAX 上传文件。该插件期望在名为“error”的 JSON 键中收到错误消息,如下所示:

{error: 'You are not allowed to upload such a file.'}

所以我在“Handler”类的“Render”方法中编写了自己的异常处理代码:

public function render($request, Exception $exception){

$err_code = $this->getExceptionHTTPStatusCode($exception);

$data = [
"error" => "Internal Server error.",
"exception" => $exception->getMessage()
];

if ($exception instanceof ValidationException){
$data['error'] = "Wrong input data";
$data['error_list'] = $exception->getResponse()-> getOriginalContent();
$err_code = 422;
}

if ($request->expectsJson()) {

return response()->json(
$data,
$err_code
);

}

return parent::render($request, $exception);
}

但是它没有按预期接收数据,而是将数组的内容放入“responseText”键值中(并且它也被转义为字符串):

{"readyState":4,"responseText":"{\"error\":\"Wrong input data\",\"exception\":\"The given data failed to pass validation.\",\"error_list\":{\"logotipo\":[\"Logotipo field is mandatory\"]}}","responseJSON":{"error":"Wrong input data","exception":"The given data failed to pass validation.","error_list":{"logotipo":["Logotipo field is mandatory."]}},"status":422,"statusText":"Unprocessable Entity"}  

我想知道是否可以将另一个键和值放在与“responseText”相同的级别中,就像“JSONResponse”一样(我不知道它是如何工作的,但它似乎是由 Laravel 的验证器附加的)但作为 JSON 对象,而不是字符串。我知道我可以用 JQuery 解析该字符串,但“Bootstrap File Input”插件期望它作为 JSON,我无法修改其代码。

我也尝试使用Vue.js资源插件,但它似乎以不同的方式读取响应,因此我的“responseText”对象被称为“body”和“bodyText”,它们具有相同的内容。我不知道为什么会收到重复的响应,一个是转义字符串,另一个是 JSON。

谢谢。

最佳答案

如果我没记错的话,您正在尝试使用ajax提交带有文件输入的表单。为此,我可以为您分享以下链接,这些人已经解决了同样的问题。

Laravel 5 Ajax File/Image Upload

AJAX file upload in laravel

Laravel 5 Ajax File/Image Upload

也许这可以为您提供一些帮助。

关于php - 在 Laravel 中将 JSON 错误消息作为 "error"对象返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com