Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"

like image 641
P.Lorand Avatar asked Dec 11 '17 13:12

P.Lorand


People also ask

How fetch data from API in React Native?

1. fetch method: The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.


1 Answers

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?

like image 104
Peter van Leeuwen Avatar answered Sep 21 '22 22:09

Peter van Leeuwen