43

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, isHeaderContentType,isRequestHeaderAuthentication,header, succesHandler, errorHandler) {
const prefix = 'link';
console.log("url:",prefix+url);
const contentType = isHeaderContentType ? {
    'Content-Type': 'application/json',
} : {};
const auth = isRequestHeaderAuthentication
    ? {
        Authorization: `Bearer ${AuthUtils.getTokenUser}`,
    }
    : {};
fetch(prefix + url, {
    method,
    headers: {
        ...contentType,
        ...auth,
        ...header,

    },
    protocol:'http:',
    body,
})
    .then(response => {
        response.json().then(json => {
            if (response.ok) {
                console.log("method", json);
                if (succesHandler) {
                    succesHandler(json)
                }
            } else {
                return Promise.reject(json)
            }
        })
    })
    .catch(err => {
        console.log("error",`${url}  ${err}`);
        if (errorHandler) {
            errorHandler(err);
        }
    })

} and call it like this

api(
            `link`,
            "GET",
            null,
            true,
            true,
            null,
            response => {
                this.setState({profile:response.data})
            },
            err => {
                console.log('error', err);
            }
        );

i call my api() inside this function:

getProfileUser = () =>{
    if (!isUserAuthenticated()){
        history.push('/signin')
    }else {
        api(
            `link`,
            "GET",
            null,
            true,
            true,
            null,
            response => {
                this.setState({profile:response.data})
            },
            err => {
                console.log('error', err);
            }
        );
    }
};

this is my full component:

export default class Profile extends Component {
constructor(props) {
    super(props);
    this.state = {
        profile:[]
    }

}
getProfileUser = () =>{
    if (!isUserAuthenticated()){
        someCode
    }else {
        api(
            `link`,
            "GET",
            null,
            true,
            true,
            null,
            response => {
                this.setState({profile:response.data})
            },
            err => {
                console.log('error', err);
            }
        );
    }
};

componentDidMount() {
    this.getProfileUser();
}

render(){
    return(
        <div>
            hello 
        </div>
    )
}

}

but when i tried to run it, i got an error like this

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

Is there anyone who knows what's wrong with my code? The function works when I use the "POST" method, but it doesn't work when I use "GET" method

15
  • When are you calling api()? Are you calling it within a component life cycle method? If so, which one?
    – Stretch0
    Mar 5, 2018 at 11:55
  • 1
    @Stretch0 yes i tried to call it on componentwillmount Mar 5, 2018 at 11:56
  • Does it work if you try calling it in componentDidMount()?
    – Stretch0
    Mar 5, 2018 at 11:57
  • 1
    @Stretch0 no,i still got the same error Mar 5, 2018 at 11:59
  • 1
    this is a weird problem, but can you try adding this? const fetch = window.fetch.bind(window); Mar 5, 2018 at 12:01

12 Answers 12

26

Double-check the value in your Authorization header for invalid characters:

This also happened to me when I tried to add an Authorization header to my fetch calls, due to an invalid character in the Authorization key.

In my case it was caused by a newline (\n) character in the header string, i.e. Bearer:\nsomelong-token. Changing the new line to a space solved the problem.

Note, that most special characters are typically not valid for authorization tokens.

3
  • 2
    Happened to me as I had an other character (the one you cannot see easily). Good hint.
    – zeropaper
    Jun 6, 2018 at 16:35
  • 1
    I use encodeURI for all headers in client and decodeURI in node. Solves the prob. Dec 30, 2019 at 2:03
  • I got this issue because I copied the Authorization header from Firefox Developer Tools without checking "raw" so the value was shortened with "..." in the middle.
    – baptx
    2 days ago
23

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...' }
3
  • 1
    This was very hard to find. Thanks for sharing, it's not obvious when this occurs!
    – tresf
    Jun 4, 2020 at 18:37
  • 1
    @tresf Knowing the suffering this inflicted on me - I'm very happy I could relieve someone else of it! Jun 5, 2020 at 7:59
  • 1
    Thanks, I had the same error. Would've never found in in my js without this.
    – Henry
    Jun 28, 2021 at 19:20
8

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
}
1
  • This seems to work. When there are unallowed characters in any of the parameters, one may run into such problems. Make sure you use trim() for your strings before passing them as arguments to any function. Most especially with REST services
    – Akah
    Mar 9, 2019 at 13:05
5

Hey I was facing the same issue while I was trying to load data using the fetch method in react.

const response = await fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    query
  })
});

I had an extra space in the Content-Type that was causing the error so please look for the same.

0
1

I got the same problem, but working with Angular 7, I was using a Interceptor service like this:

// headerservice.ts
public intercept() {
    const token = Cookies.get('token');
    this.Language = Cookies.get('language');
    this.headers = new HttpHeaders(
      {
        Authorization: 'JWT ' + token,
        'Accept-Language': this.Language
      }
    );
    return this.headers;
  }

  //other file 
   this.headers = this.headersService.intercept();

But it doesn´t work on the other file where i am doing the fetch, so i remove the service and put the headers directly inside the function and it works! like this:

const token = Cookies.get('token');
const language = Cookies.get('language');
const headers = { 
 Authorization: 'JWT ' + token,
'Accept-Language': language
}
const fetchParams = { method: 'GET',
           headers: (headers) };
fetch(url, fetchParams)
1

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

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

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

0

In my case it occurred because I wrote "Content Type" instead of "Content-Type"

0

I got this error when I stringified my headers like this:

fetch(http://example.com,
{
    credentials: "include",
    headers: JSON.stringify({
        foo: localStorage.getItem("foo"),
    }),
})

I fixed it by removing the JSON.stringify:

fetch(http://example.com,
{
    credentials: "include",
    headers: {
        foo: localStorage.getItem("foo"),
    },
})
0

I had faced similar issue- "Undocumented TypeError: Failed to execute 'fetch' on 'Window': Value is not a valid ByteString."

while testing with Swagger. It got resolved after I checked my token that has ... in between. Please be sure to copy token from Web browser they tend to put elipsis(...) if string is long.

1
  • Another reason could be your are not copying entire token.. check token value thoroughly to identify cause.. Generally in chrome browser token shown under SSOToken{ tkn is short one and below after sub tkn is correct Jul 1, 2021 at 8:34
-2

For me the solution was to not send body on GET method.

async request(url, method, data) {
    const options = {
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        method: method,
        credentials: "include"
    };

    if (['POST', 'PUT', 'DELETE'].includes(method)) {
        options.body = JSON.stringify(data);
    }

    return await fetch(url, options);
}
1
  • 1
    Could you provide the code sample you used for future reference by others? Mar 1, 2021 at 14:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.