【问题标题】:Is it possible to make a request while reading a file from a URL?从 URL 读取文件时是否可以发出请求?
【发布时间】:2021-05-03 22:33:51
【问题描述】:

执行请求时是否可以从 URL 读取文件?

var options = {
    'method': 'POST',
    'url': 'http://172.19.64.193:8080/services/update?id=AkDwkm5bKo0ARvuvTaM7yj',
    'headers': {
        'Authorization': 'Bearer ' + authToken
    },
    formData: {
        'Filedata': {
            'value': fs.createReadStream('image.jpg').pipe(request.put('https://www.worldcocoafoundation.org/wp/uploads/image.jpg')),
            'options': {
                'filename': '7798153810500.jpg',
                'contentType': null
            }
        }
    }
};
request(options, function (error, response) {
    if (error) throw new Error(error);
    console.log(response.body);
});

使用 pipe() 进行 createReadStream 时,会抛出错误:

TypeError: request.put is not a function

【问题讨论】:

  • request 来自哪里?你能显示定义该变量的代码吗?看来您可能不小心用同名的 NPM 模块以外的东西覆盖了 request 变量,因此,没有 .put() 方法,因为这个 request 变量不是 request来自 NPM 的模块,还有别的。
  • 你去哪儿了?请不要只是发布和消失。如果您这样做,我们将无法帮助您。
  • 是的,请求已被覆盖。但现在我收到错误:错误:ENOENT:没有这样的文件或目录,打开'image.jpg'
  • 如果您说这个fs.createReadStream('image.jpg') 生成ENOENT,那么在当前目录中找不到image.jpg 是不言自明的。也许它需要一条正确的路径?或者,您的代码还没有完成?
  • 不是从网址读取然后下载的吗?

标签: node.js request fs


【解决方案1】:

从您得到的错误来看,request 符号似乎被其他定义覆盖,因此不是您期望的 request 库。

您需要更改覆盖它的变量/函数参数名称,以免它们发生冲突。

【讨论】:

    猜你喜欢
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多