jsontypescriptreact-nativefetch-api

typescript Cannot add headers to a fetch api using react-native


I am using Fetch API from react-native and I am using typescript. My code looks like this:

let responseLogin = await fetch('http://url_example', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: requestBody
    });

But I get the following error where the header is:

 Argument of type '{ method: string; headers: { 'Content-Type': string; }; body: string; }' is not assignable to parameter of type 'RequestInit'.
  Types of property 'headers' are incompatible.
    Type '{ 'Content-Type': string; }' is not assignable to type 'Headers | string[][]'.
      Object literal may only specify known properties, and ''Content-Type'' does not exist in type 'Headers | string[][]'.

I have also tried to create a custom header but without any luck:

    let requestHeaders = new Headers();
        requestHeaders.set('Content-Type', 'application/json');
        // I have also tried adding this at the end but no luck 
        // requestHeaders.get('Content-Type');

How could I add a header to this? Because I cannot find any way to make this happen and I don't know what is the problem. If I test these in postman, I get a 200 response, here I get a 401 response. I have also tried this library just to add custom headers: https://www.npmjs.com/package/fetch-headers

I use: Visual studio code 1.81.1 "react-native": "0.50.0", "typescript": "2.6.1"


Solution

  • Can you try typing it as HeadersInit?

    const requestHeaders: HeadersInit = new Headers();
    requestHeaders.set('Content-Type', 'application/json');
    
    const responseLogin = await fetch('URL', {
      method: 'POST',
      headers: requestHeaders,
      body: requestBody
    });
    

    If not, can you show the error you are getting when you are initiating it with the Headers() constructor, you showed in the question?