Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make request body type compatible with RequestInit or BodyInit when using node-fetch?

I started to use Typescript for my nodejs project. For accessing some external API, I use node-fetch to make requests. While setting up a PUT request, an error pops up, saying that the given body is not assignable to type RequestInit:

The error:

Error:(176, 28) TS2345:Argument of type '{ headers: Headers; method: string; body: MyClass; }' is not assignable to parameter of type 'RequestInit'.
  Types of property 'body' are incompatible.
    Type 'MyClass' is not assignable to type 'BodyInit'.
      Type 'MyClass' is not assignable to type 'ReadableStream'.
        Property 'readable' is missing in type 'MyClass'.

MyClass:

class MyClass {
  configId: string;
  adapterType: string;
  address: string;

  constructor(configId: string, adapterType: string, address: string) {
    this.configId = configId;
    this.adapterType = adapterType;
    this.address = address;
  }

  // some methods
}

Invocation:

let body = new MyClass("a", "b", "c")
let url = config.url + "/dialog/" + dialogId
let headers = new Headers()
// Append several headers

let params = {
  headers: headers,
  method: "PUT",
  body: body
}

return new Promise((resolve, reject) => {
  Fetch(url, params) // <-- error is shown for params variable
    .then(res => {
      // Do stuff
      resolve(/*somevalue*/)
    })
}

How should I make the body object compatible?

like image 810
Leon Joosse Avatar asked May 16 '17 09:05

Leon Joosse


People also ask

How do you pass a body in GET request in node?

If you use GET , you can't have body, you just have query. You can convert your query to string and add to your url, or use option with qs : option = { url: 'your_url', qs: your_query }; request(option, (error,res)=>{}); If want use body, you should use POST .

Can you use the fetch API in node?

Fetch() support is now available in Node. js as an experimental core feature. Fetch() is a well-liked cross-platform HTTP client API that functions in browsers and Web/Service Workers.

What is Requestinit?

A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL.


1 Answers

You need to stringify your body:

let params: RequestInit = {
  headers: headers,
  method: "PUT",
  body: JSON.stringify(body)
}
like image 80
Ruslan Korkin Avatar answered Sep 21 '22 18:09

Ruslan Korkin