Ash*_*own 1 javascript fetch laravel sweetalert2
编辑:你误解了。考虑这个伪代码。这基本上是我想要做的,但是当这样写时它不起作用。
使用 Fetch 收到 Laravel 422 响应后,将response不包含实际的 JSON 数据。您必须使用response => response.json()才能访问它。我已经放了一张照片,response我还提供了使用后的输出response => response.json()。
我不想将对象转换为 JSON 字符串。
我在 Laravel 中使用 SweetAlert2。
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));
}
})
Run Code Online (Sandbox Code Playgroud)
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."]}}
Run Code Online (Sandbox Code Playgroud)
我进行了 AJAX 调用,如果 Laravel 的验证失败,它会status 422以 JSON格式返回带有验证错误消息的 。但是,Fetch 不会将422响应计为“错误”,因此我必须自己手动触发它throw。
因为我的验证消息在JSON响应中,即
then(response => json())
如何将我的转换response为 tojson然后将其传递给我的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)
})
})
Run Code Online (Sandbox Code Playgroud)