typescript Cannot add headers to a fetch api using react-native
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 };
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)
// ...
}
I solved the problem by importing Headers
like this:
import fetch, { Headers } from 'node-fetch';
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?