'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 1:[1]

What TypeScript libraries are you including with your build? It looks like your definition for the headers property is wrong. In TypeScript 2.6.2, the headers property is of type HeadersInit, which is defined as: type HeadersInit = Headers | string[][] | { [key: string]: string };

Solution 2:[2]

i solved the problem importing, like this

import fetch,{Headers} from 'node-fetch';

Solution 3:[3]

I have solved the problem like this:

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

All that I had to do was to ignore that error message because JS interprets the syntax correctly, only typescript doesn't and I did that by creating a variable in which I stored those two strings.

Solution 4:[4]

The accepted answer has the caveat that it doesn't handle the scenario where you encapsulate fetch into a function of your own that receives the same arguments as fetch and sets defaults to the headers property. For example:

async function myFetch(input: RequestInfo, init: RequestInit) {
  // set some headers here
  const res = await fetch(input, init)
  // return something from the response here, handle errors
}

The problem with the resolved answer is that RequestInit.headers is of type HeadersInit whose definition is:

type HeadersInit = string[][] | Record<string, string> | Headers;

When I try to set defaults for headers but still use headers passed by the calling function, I run into issues because of these possible multiple types that I need to deal with.

What I resolved out of complete exasperation is to define my own RequestInit type where headers is only Record<string, string>. I don't care about the other types, an object of string key/values IS fine.



export interface MyRequestInit extends Omit<RequestInit, 'headers'> {
  headers?: Record<string, string>;
}

export async function fetchJson<JSON = unknown>(
  input: RequestInfo,
  init: MyRequestInit = {},
) {
  // set my own default headers here
  const res = await fetch(input, init)
  // ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 A. Goodale
Solution 2 Camilo Andres Perez Sanchez
Solution 3 adiga
Solution 4