I need to send a file as part of a POST
request in Node.js and I don't want to use other packages or external libraries but plain http
(https
) module, part of the standard Node.js API.
From the Node.js doc, an example
This example in the Node.js doc, hints about what I want to achieve:
const postData = querystring.stringify({'msg': 'Hello World!'});
const options = {
hostname: 'http://localhost',
port: 8080,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(postData);
req.end();
What I want
This example is very close to what I want to achieve, the only difference is in the very first lines:
const postData = querystring.stringify({'msg': 'Hello World!'}); // <== I want to send a file
Instead of sending a string, I want to send a file. The doc page says that it should be possible:
http.request()
returns an instance of thehttp.ClientRequest
class. TheClientRequest
instance is a writable stream. If one needs to upload a file with aPOST
request, then write to theClientRequest
object.
How can I do this?
Attempts
I have tried:
clientRequest.write(fs.createReadStream("C:/Users/public/myfile.txt"));
clientRequest.end();
But I get this error:
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type object