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”

问题评论:

    
does it require any credentials to be send ?
    
have you tried using headers: { Accept: 'application/json', 'Content-Type': 'application/json', } in the fetch api
    
you may need to add credentials: 'include' in the fetch request if you are sending credentials
    
@Niladri I am sending a username and a password. Yes I have tried with your second suggestion and it said the same thing. I have not tried with credentials, I will trie and come back with an answer.
– P.Lorand
2 hours ago
    
@Niladri I have tried with credentials: ‘include’, it is still not working.
– P.Lorand
1 hour ago

答案:

答案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 };

答案评论:

    
I have tried to add the headers like this: headers: [[‘Content-Type’] , [‘application/json’]]. Still it returns a status of 401.
– P.Lorand
30 mins ago
    
I have also tried this library: npmjs.com/package/fetch-headers
– P.Lorand
30 mins ago

原文地址:

https://stackoverflow.com/questions/47754183/typescript-cannot-add-headers-to-a-fetch-api-using-react-native

添加评论

友情链接:蝴蝶教程