繁体   English   中英

如何使用请求库在Node.js中执行此curl操作

[英]how to do this curl operation in Node.js using request library

如何使用请求Node.js库转换此curl操作:

curl -L -X GET -H "Content-Type:application/json" -H "Authorization: authorization..." -H "Scope: 11111111" https://url/download >> file.gz

    /*the -L is curl option which means --location      Follow redirects (H)
         --location-trusted  Like '--location', and send auth to other hosts (H)*/

如果只想下载到文件,则可以使用请求类型。

该请求将如下所示:

request.head({
    url: "https://url/download",
    followAllRedirects: true,
    headers: {
    'Content-Type': 'application/json',
    'Authorization':'authorization...',
    'Scope': '11111111'
  }
}, (err, res, body) => {
  request('https://url/download')
    .pipe(fs.createWriteStream(`tmp/${res.path}`)).on('close', (data, err) => {
            if(err) console.log(`Unable to write to file ${err}`)
            console.log('Done')
    })
})

我使用了类似的片段,效果很好

使用Postmans代码生成器

在此处输入图片说明

  1. 点击左上角的代码
  2. 粘贴您的卷曲请求
  3. 从弹出式窗口左上方的下拉列表中选择Node.js Request
  4. 然后,您应该从工作的cURL请求中获取JS代码段转换

这是我们必须将请求放入另一个解决方案的解决方案,因为:因此,第一个请求返回url,第二个请求将下载文件

const options = {
  url: url,
  headers: {
    Authorization: `auth`,
    'scope': profileId,
    'content-type': 'application/json'
  },
};
const r = request.get(options, async (err, res, body) => {
    const fileStream = fs.createWriteStream(`${path}.gz`);
    request(res.request.uri.href).pipe(fileStream);
    // path exists unless there was an error
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM