fetch resolves even if 404?

前端 未结 4 630
走了就别回头了
走了就别回头了 2020-11-27 07:22

Using this code :

fetch(\'notExists\') // <---- notice 
    .then(
        function(response)
        {
           alert(response.status)
        }
    )         


        
4条回答
  •  悲&欢浪女
    2020-11-27 07:45

    Building on @fernando-caravajal example (which resulted easier for me for the async/await use) I made this slightly modified version below, for a post query, with parameters sent. I added the throw new Error statement as I had trouble to catch the failure on response.ok == false.

    /**
     *  Generic fetch function
     */
    function fetchData(url,parameters,callback) {
    
      fetch(url,{
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(parameters),
      })
      .then(async(response) => {
          // status 404 or 500 will set ok to false
          if (response.ok) {
              // Success: convert data received & run callback
              result = await response.json();
              callback(result);
          }
          else {
              throw new Error(response.status + " Failed Fetch ");
          }
      }).catch(e => console.error('EXCEPTION: ', e))
    }
    

提交回复
热议问题