编辑:您误解了。考虑这个伪代码。这本质上是我想做的,但这样写是行不通的。
一旦您收到带有 Fetch 的 Laravel 422 响应,响应
不包含实际的 JSON 数据。您必须使用 response => response.json()
来访问它。我放了一张response
的图片,我还提供了使用response => response.json()
后的输出。
我不是尝试将对象转换为 JSON 字符串。
我在 Laravel 中使用 SweetAlert2。
抛出错误(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()
之后包含以下内容,我想将此 JSON 传递给 error()
.
{"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
响应中,即
然后(响应 => json())
如何将我的 response
转换为 json
然后将其传递给我的 throw error()
?
仅供引用,这是 console.log(response)
在使用 response => response.json()
之前保存的内容
最佳答案
像这样的东西应该可以工作:
fetch(...)
.then((response) => {
return response.json()
.then((json) => {
if (response.ok) {
return Promise.resolve(json)
}
return Promise.reject(json)
})
})
关于javascript - 如何使用 then() 将 Fetch 响应的 JSON 主体传递给 Throw Error()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50041257/