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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With