javascript - 如何使用 then() 将 Fetch 响应的 JSON 主体传递给 Throw Error()?

标签 javascript laravel fetch-api sweetalert2

编辑:您误解了。考虑这个伪代码。这本质上是我想做的,但这样写是行不通的。

一旦您收到带有 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));
  }
})

responseresponse => 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() 之前保存的内容 enter image description here

最佳答案

像这样的东西应该可以工作:

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/

相关文章:

JavaScript 仅当 div 类存在时才向 div 添加样式

javascript - Node.JS 中的同步 "GET"

php - 使用 Docker 容器部署 Laravel

json - Vue 获取 response.json promise 不会创建响应式(Reactive) setter/getter

javascript - 使用 fetch API 请求 blob 图像并转换为 base64

javascript - 加载页面以提高性能的最佳方法

javascript - 如何直接改变一个CSS类?

laravel - 只有在所有其他规则都通过时才添加验证规则,或者在 Laravel 5.7 中出现第一个错误时停止验证整个属性集

laravel - 如何在 Laravel 5.6 中创建自定义帮助文件?

Javascript - 如何静默检索不响应 fetch() 请求的网页源