Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add body to ClientRequest on Electron

I would like to use ClientRequest with Electron. I want to add a body to my request, but I see no information about body in the documentation.

My request object:

  const requestApi = {
    method,
    headers,
    protocol: process.env.API_PROTOCOL,
    hostname: process.env.API_HOSTNAME,
    port: process.env.API_PORT,
    path: `${process.env.API_PATH}${slug}`,
    body,
  };

And my request:

request.on('response', data => {
  console.log('---------------------');
  console.log(data);

  data.on('data', chunk => {
    console.log(chunk);
  });
  data.on('end', () => {
    console.log('No more data in response.');
  });

  if (data.statusCode === 200) {
    event.sender.send('api-response');
  }
});

request.end();

When I console.log(data), the data is an empty array data: [].

Can anyone help me ? :)

Thank you!

like image 653
s-leg3ndz Avatar asked Feb 18 '26 04:02

s-leg3ndz


1 Answers

ClientRequest is a Writable Stream. The way to send body data to a Writable Stream is to use .write() and .end(). You can see these functions in the API documentation: ClientRequest.write() and ClientRequest.end(). The argument chunk is where your data should go.

In your example, that might look like this:

const requestApi = {
  method,
  headers,
  protocol: process.env.API_PROTOCOL,
  hostname: process.env.API_HOSTNAME,
  port: process.env.API_PORT,
  path: `${process.env.API_PATH}${slug}`,
};

const request = new ClientRequest(requestApi);

request.on('response', data => { /* ... */ });

request.end(body);
like image 96
Andrew Myers Avatar answered Feb 19 '26 18:02

Andrew Myers