Reputation: 3528
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!
Upvotes: 3
Views: 7821
Reputation: 2786
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);
Upvotes: 2