如何使用 then() 将 Fetch 响应的 JSON 正文传递给 Throw Error()?

2024-05-18

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() enter image description here


像这样的东西应该有效:

fetch(...)
  .then((response) => {
    return response.json()
      .then((json) => {
        if (response.ok) {
          return Promise.resolve(json)
        }
        return Promise.reject(json)
      })
  })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 then() 将 Fetch 响应的 JSON 正文传递给 Throw Error()? 的相关文章

随机推荐