EDIT:你误会了。考虑这个伪代码。这本质上是我想做的,但这样写是行不通的。
一旦您使用 Fetch 收到 Laravel 422 响应,response
不包含实际的 JSON 数据。你必须使用response => response.json()
来访问它。我已经放了一张照片response
成立,我还提供了使用后的输出response => response.json()
.
I am NOT尝试将对象转换为 JSON 字符串。
我将 SweetAlert2 与 Laravel 一起使用。
throw error(response => response.json())
swal({
title: 'Are you sure you want to add this resource?',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Submit',
showLoaderOnConfirm: true,
allowOutsideClick: () => !swal.isLoading(),
preConfirm: () => {
return fetch("/resource/add", {
method: "POST",
body: JSON.stringify(data),
credentials: "same-origin",
headers: new Headers({
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'Content-Type': 'application/json',
'Accept': 'application/json'
})
})
.then(response => {
if (!response.ok) {
// How can I return the response => response.json() as an error?
// response.json() is undefined here when used
// throw Error( response => response.json() ); is what I want to do
throw Error(response.statusText);
}
return response;
})
.then(response => response.json())
.then(res => console.log('res is', res))
.catch(error => console.log('error is', error));
}
})
response
之后持有以下内容response => response.json()
我想要传递的就是这个 JSONerror()
.
{"message":"The given data was invalid.","errors":{"name":["The name field is required."],"abbrev":["The abbrev field is required."]}}
我进行 AJAX 调用,如果 Laravel 的验证失败,它会返回status 422
以及 JSON 格式的验证错误消息。但是,Fetch 不算422
响应为“错误”,所以我必须自己手动触发它throw
.
因为我的验证消息位于JSON
响应即then(response => json())
我怎样才能转换我的response
to json
然后将其传递给我的throw error()
?
Just FYI, this is what console.log(response)
holds before using response => response.json()