Using React Native, it is not possible to include headers in a fetch API request

Currently, I am utilizing the Fetch API in react-native along with typescript. The code snippet I am working with looks like this:

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

However, upon running the code, I encounter an error related to the header section:

 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 attempted creating a custom header as well but unfortunately, it did not yield any positive results:

    let requestHeaders = new Headers();
        requestHeaders.set('Content-Type', 'application/json');
        // Additional attempt that was made but didn't resolve the issue 
        // requestHeaders.get('Content-Type');

Is there a way to successfully add a header in this scenario? I've tried various methods without success and cannot pinpoint the exact cause of the problem. While testing in postman yields a 200 response, executing the code produces a 401 response. I also experimented by using the library 'fetch-headers' to include custom headers: https://www.npmjs.com/package/fetch-headers

Tools being used: Visual studio code version 1.81.1 "react-native": "0.50.0", "typescript": "2.6.1"

Answer №1

Could you attempt entering 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 that doesn't work, can you please share the error message you receive when trying to initialize it with the Headers() constructor mentioned in your original question?

Answer №2

Which TypeScript libraries have been integrated into your project's build process? It seems like there may be an issue with how you've defined the headers property. According to TypeScript 2.6.2 specifications, the correct type for the headers property should be HeadersInit, as outlined below:

type HeadersInit = Headers | string[][] | { [key: string]: string };

Answer №3

To resolve the issue, I successfully tackled it by bringing in the Headers module through this method:

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

Answer №4

The solution provided in the accepted answer lacks handling for a specific scenario where the fetch function is encapsulated within a custom function that takes the same arguments as fetch and sets defaults for the headers property. Here's an example:

async function myFetch(input: RequestInfo, init: RequestInit) {
  // set default headers
  const res = await fetch(input, init)
  // handle response and errors here
}

The issue with this approach is that the type of RequestInit.headers is defined as HeadersInit, which can be of various types such as string arrays, key-value pairs, or Headers objects.

To address this, I created a custom MyRequestInit type where the headers property is strictly defined as Record<string, string>. This simplifies the handling of headers to just an object with string key-value pairs.



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

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

Answer №5

I encountered a similar issue, but the solution provided did not work for me because headers may have already been initialized. Therefore,

    if (!requestInit.headers) {
      requestInit.headers = new Headers()
    }

    requestInit.headers.set('Content-Type', 'application/json')
    // *TS2339: Property 'set' does not exist on type 'HeadersInit'. Property 'set' does not exist on type 'string[][]'*

This results in a compilation error, as mentioned by others, because HeadersInit is defined as

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

SOLUTION: use constructor with parameter

requestInit.headers = new Headers(requestInit.headers)
requestInit.headers.set('Content-Type', 'application/json')

Answer №6

In the year 2024, your inquiry remains relevant and now there is an option to convert the item you provide as a HeadersInit:

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

Personally, I have found that by using this cast, the error messages from tsc no longer persist. Although, it should be noted that my analysis was conducted with tsc version 5.6.3 rather than 2.6.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Comparing dates for equality in Sequelize - a comprehensive guide

Can someone help me with comparing equality between two dates in my code? I have attempted the following but it does not seem to work: const result: SomeModel= SomeModel.findOne( {where: { startTime : { [ ...

Continuously display the keyboard upon pressing the submit button on the keyboard

Is there a way to keep the keyboard open after pressing submit? I want the keyboard to stay visible even after the submit action is completed. <TextInput style={{ height: 40, borderColor: 'gray', borderWidth: 1 }} onChangeTe ...

Problem with Typescript reducer

Below is a snippet of my code: ... type RepairsState = { data: Property[] /* Property object from external file */ } type RepairsPropertyLoadAction = { type: typeof REPAIRS_PROPERTY_LOAD payload: { models: Property[] } /* payload will contain an a ...

Angular 2 iframe balked at being shown

Whenever I enter a URL into a text input and press enter, my objective is to have the URL open in an iframe. However, some websites produce an error when trying to do so. Is there a method to successfully display a web page in an iframe? Error message: Th ...

Verifying the presence of a JSON response row in Python

Displaying my JSON response below: {u'kind': u'bigquery#queryResponse', u'rows': [{u'f': [{u'v': u'1'}, {u'v': u'1607'}, {u'v': u'coriolanus'}]}, {u&apos ...

The script resource is experiencing a redirect that is not permitted - Service Worker

I have integrated a Service Worker into my Angular application, and it works perfectly when running on localhost. However, when I attempt to deploy the code in a development or different environment, I encounter the following error: Service worker registra ...

Using Javascript arrays to assign values to a Json object in CanvasXpress

I'm seeking advice on the best source for assistance with CanvasXpress. I haven't found any relevant threads in the forum yet. Currently, I'm using CanvasXpress to showcase dynamic data and I know that it accepts json objects. My issue arise ...

By utilizing custom typeRoots while continuing to export these types alongside the entry point

For my project setup, I employ rollup to bundle an associated index.d.ts (and index.js) for the entrypoint src/index.ts. Within the project structure, there exists a directory named src/types containing multiple .d.ts files. These types are globally acces ...

Dividing a JSON array into two separate rows with Spark using Scala

Here is the structure of my dataframe: root |-- runKeyId: string (nullable = true) |-- entities: string (nullable = true) +--------+--------------------------------------------------------------------------------------------+ |runKeyId|entities ...

accessing all records through a RESTful API

I have a unique question regarding REST API pagination. I have written a script to extract specific data from this page: import requests import json import pandas as pd url = 'http://data.rcsb.org/rest/v1/core/entry/5XTI' r = requests.get(url) ...

gson returns null if not deserialized

Issue with Gson deserialization when not handling specific fields public class Mode { @Expose(deserialize = false) public final List<String> list; public Mode(List<String> list) { this.list = list; } public List< ...

Is there a way to change the color of a number's font based on whether it is preceded by a "+" or "-" sign?

I am currently working on a stocks widget and I have a specific requirement. Whenever there is a change in value in the Change or Changeinpercent columns, I need to dynamically set the font color to red for a decrease (-) or green for an increase (+). Her ...

TS2339: The 'map' property is not available on the 'Object' type

I'm currently working with the following code snippet: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/op ...

"JSON utilizing the 'hide' option, along with an '

I am currently in the process of creating a registration form that includes two divs with images, #onimg and #offimg. When a user enters an available username, the #offimg div will be displayed, while if they choose a username that is already taken, the #o ...

Is NSJSONSerialization.JSONObjectWithData altering the retrieved data?

func getData(englishWord : String, completionHandler : (success: Bool, data : [String : AnyObject]?, errorString : String?) -> Void) { let apiURL = "https://api.pearson.com/v2/dictionaries/ldoce5/entries?headword=vodka" let urlString = a ...

Using json_encode in PHP results in nullification of HTML strings

I am working with an array that includes a string containing HTML tags as one of its elements. As I loop through the array and output the field, I can see the string. $positions = $jobs_dbc->getData($sql); foreach($positions as $position) { ...

Python 3.6 encountering issues with converting string to json format

My challenge involves converting the string below to JSON using json.loads(): targetingConditions = "[{\"filters\":[{\"key\":\"domain\",\"rel\":\"neq\",\"values\":['science.howstuffworks.com ...

Error TS2305: The module "@prisma/client" does not have an export named "User"

Setting up a Gitlab CI for my nestjs project using prisma has been my current challenge. I keep encountering this error when running the pipeline: see image here This is what my .gitlab-ci.yml looks like: image: node:latest stages: - build build: st ...

Exploring the power of nesting views using *ngFor in Ionic framework

I am looking to design a screen that features nested views using the *ngFor loop. The data I have is in a two-dimensional array format and I want to iterate through it to display the same view for each row within each section. It should look something like ...

What is the best way to incorporate this idea into Python code?

https://i.sstatic.net/HAwj0.png I have data stored in a pandas dataframe and I need to generate a JSON structure following the hierarchy mentioned in the pathString column. Can someone guide me on how to achieve this using Python? { "name":"world", ...