简体   繁体   English

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

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

How can I convert this curl operation using request Node.js 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)*/

If you just want to download to a file, you can use a head request type. 如果只想下载到文件,则可以使用请求类型。

The request will look like so: 该请求将如下所示:

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')
    })
})

I have used a similar snippet which worked well 我使用了类似的片段,效果很好

Use Postmans code generator 使用Postmans代码生成器

在此处输入图片说明

  1. Click code on the top left 点击左上角的代码
  2. Paste your curl request 粘贴您的卷曲请求
  3. Select Node.js Request from dropdown on top left of popup 从弹出式窗口左上方的下拉列表中选择Node.js Request
  4. You should then get JS snippet converted from your working cURL request 然后,您应该从工作的cURL请求中获取JS代码段转换

Here is the solution we have to put request inside another because: so the first request returns the url and the second one will download the file 这是我们必须将请求放入另一个解决方案的解决方案,因为:因此,第一个请求返回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