繁体   English   中英

如何通过then()将Fetch响应的JSON主体传递给Throw Error()?

[英]How can I pass JSON body of Fetch response to Throw Error() with then()?

编辑:您误会了。 考虑这个伪代码。 这本质上就是我想要做的,但是当这样写的时候它是行不通的。

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

responseresponse => response.json()之后保存以下内容,这是我要传递给error() JSON。

{"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转换为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)
      })
  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM