Search code examples
node.jspostpostmannode-fetch

node-fetch send post body as form-data


I am trying to send a POST request with body as form-data since this seems to be the only way that works.

I tried this in Postman too and sending body as raw JSON didn't work.

So I tried doing the same with node-fetch but seems like body is being sent as JSON and I'm getting the same error as before (when using raw from Postman).

try{
  const { streamId } = request.body;
  const headers = {        
    "Authorization": INO_AUTHORIZATION_CODE,
    // "Content-Type": "multipart/form-data; boundary=<calculated when request is sent>"
    "Content-Type": "application/json"
  }      
  const url = `https://www.inoreader.com/reader/api/0/stream/contents/${streamId}`;
  const body = {
      AppId: INO_APP_ID,
      AppKey: INO_APP_KEY
  }
  
  const resp = await fetch(url, {
      method: 'POST',
      body: JSON.stringify(body),
    //   body: body,
      headers: headers
    });   
    
  const json = await resp.text();
  return response.send(json);
} catch(error) {
    next(error);
}

Only setting body as form-data works:

enter image description here


Solution

  • You need to use the form-data package as mentioned in their doc so your code will be

    const FormData = require('form-data');
    
    const form = new FormData();
    form.append('AppId', INO_APP_ID);
    form.append('AppKey', INO_APP_KEY);
    
    const resp = await fetch(url, {
          method: 'POST',
          body: form
        });