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

时间:2018-04-11 09:00:08

标签: node.js curl request

如何使用请求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)*/

2 个答案:

答案 0 :(得分:1)

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

请求将如下所示:

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代码生成器

enter image description here

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

答案 1 :(得分:0)

以下是我们将请求放入另一个请求的解决方案,因为:所以第一个请求返回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
  });