javascript - 如何使用 http(s) 模块在 Node.js 的请求中发送文件?
问题描述
我需要在 Node.js 中将文件作为POST
请求的一部分发送,并且我不想使用其他包或外部库,而是使用普通http
( https
) 模块,这是标准 Node.js API 的一部分。
来自 Node.js 文档,一个示例
Node.js 文档中的这个示例暗示了我想要实现的目标:
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();
我想要的是
这个例子非常接近我想要实现的,唯一的区别在于第一行:
const postData = querystring.stringify({'msg': 'Hello World!'}); // <== I want to send a file
我想发送一个文件,而不是发送一个字符串。文档页面说应该可以:
http.request()
返回该类的一个实例http.ClientRequest
。该ClientRequest
实例是一个可写流。如果需要通过POST
请求上传文件,则写入ClientRequest
对象。
我怎样才能做到这一点?
尝试
我努力了:
clientRequest.write(fs.createReadStream("C:/Users/public/myfile.txt"));
clientRequest.end();
但我得到这个错误:
TypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是字符串或缓冲区类型之一。接收到的类型对象
解决方案
我不确定您是否正确使用了流。尝试这个:
fs.createReadStream(filePath).pipe(req);
推荐阅读
- java - 在单元测试期间找到资源文本文件,但在从 Netbeans 运行程序时未找到
- wordpress - 无法连接到本地 wordpress 服务器
- c# - NLog 未写入事件日志 .NET Core 2.1
- javascript - JavaScript 函数存在但未被调用
- sql - SQL 存储过程超时
- django - 将 React 流量重定向到开发中的 Django REST
- android - 在哪里/如何确定聊天消息是发送还是接收(android)
- azure - 如何从 luis 读取/访问情绪分析结果
- c# - 使用 linq any 检查列表中是否包含
- python - Pandas - 在多列上使用`.rolling()`