TypeError: Failed to execute 'fetch' on 'Window': Invalid value

后端 未结 8 635
情歌与酒
情歌与酒 2020-12-24 14:24

I\'ve tried to use fetch to call from backend using react, without libs (such as Axios). So I created this function:

export function api(url, method, body, i         


        
8条回答
  •  情深已故
    2020-12-24 15:20

    For me, the error occurred because I included a "body" on a GET request when calling fetch(). Excluding the body for GET requests solved the problem (e.g., if you're writing a generic function or framework that handles different HTTP request types). Here's a simple code excerpt to illustrate the solution (obviously this code would need expansion in the real world, but it makes the point):

    // Earlier code that specifies the HTTP method
    let method = 'GET';
    
    // Create fetch() init object
    let fetchInit = {};
    if (method !== 'GET') {
      fetchInit.body = yourRequestBody;
    }
    
    // Start network request
    fetch(url, fetchInit).then...
    

提交回复
热议问题