【问题标题】:Fetch throwing error with 302 in componentdidmount react在componentdidmount反应中使用302获取抛出错误
【发布时间】:2017-10-26 01:30:01
【问题描述】:

当 api 调用重定向并返回响应时,我在 componentDidMount 方法中使用 fetch 方法时遇到问题。最初的 302 响应试图在获取并抛出 JSON.parse:JSON 数据的第 1 行第 1 列的数据意外结束之后在 then 方法中进行处理。关于如何解决此问题的任何建议?

componentDidMount(){
            let config = {
                method: 'GET',
                mode: 'no-cors',
                redirect:'follow',
                cache: 'default',
                headers: new Headers({
                    'Content-Type': 'application/json'
                })
            };

         fetch("ACTUAL_URL",config)
         .then(response => response.text())
         .then( val => JSON.parse(val))
         .then(response => {
                    this.setState({val:response.json()})
            })
    }

API 调用响应 -302 - 200

【问题讨论】:

  • 注意:response.json() 是一个 Promise,所以这可能不是你想要做的——如果有东西试图 JSON.parse 那个 val,它会试图解析字符串"[object Promise]" - 显然 JSON 无效。如果这确实是问题,请阅读how to use fetch
  • 302 返回一个未定义的对象并尝试转换该 json 导致问题。
  • 是的。这是您代码中的另一个错误

标签: javascript reactjs


【解决方案1】:

fetch 仅在网络错误的情况下拒绝。对于其他情况,您必须使用 好的方法

fetch("ACTUAL_URL",config)
         .then(function(data){
              if (!data.ok) {
               throw Error(data);
              }
         }).then(response => response.text())
         .then( val => JSON.parse(val))
         .then(response => {
                    this.setState({val:response.json()})
         }).catch(function(error){
           // handle the 302 error here
         })

【讨论】:

    猜你喜欢
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 2018-11-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多