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

后端 未结 8 567
情歌与酒
情歌与酒 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:04

    For me, i had an invalid character in a key of the header object. I accidentally included the ":" and this throws the error described. Really difficult to visually see in the chrome console. Hope it helps someone.

    { 'Authorization:':'Bearer etc...' }
    
    0 讨论(0)
  • 2020-12-24 15:05

    This also happened to me when I tried to add an Authorization header to my fetch calls. In my case it was caused by a newline character in the header string, i.e. Bearer:\nsomelong-token. Changing the new line to a space solved the problem.

    0 讨论(0)
  • 2020-12-24 15:11

    i've solve this problem with adding my frontend url to whitelist cors of my backend code

    0 讨论(0)
  • 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...
    
    0 讨论(0)
  • 2020-12-24 15:22

    I had this when passing a string with a newline character into the header object for example:

    const myString = 'this is a string \nand this is a new line';
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
        'subscriptionId': myString
    }
    
    0 讨论(0)
  • 2020-12-24 15:23

    This error happened to me as well, however with different circumstances. I would like to share it in case someone else has this issue.

    So I got the error "TypeError: Failed to execute 'fetch' on 'Window': Invalid value" when I tried to upload a file with HTTP POST without using FormData. To solve the issue I used FormData object and appended properties and file itself:

    let formData = new FormData();
    formData.append('name', fileName);
    formData.append('data', file);
    

    then I used fetch to send the file with POST method. Here is pseudo code:

    const options = {method: 'POST', formData};
    fetch('http://www.someURL.com/upload', options);
    
    0 讨论(0)
提交回复
热议问题