javascript 将 cURL 请求转换为 node.js 的请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30491525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:15:51  来源:igfitidea点击:

Convert cURL request to request of node.js

javascriptnode.jscurlrequesthttprequest

提问by Ilshat

Here is my valid cURL command:

这是我的有效 cURL 命令:

curl 'https://www.example.com/api/' --data '{"jsonrpc":"2.0","method":"getObjectsByFilter","id":"3"}'

here is what I tried in Node.js:

这是我在 Node.js 中尝试过的:

var url = 'https://www.example.com/api/';

var data = {
  "jsonrpc":"2.0",
  "id":"3"
};

req.post({ url: url, form: data}, function (err, result, body) {

But it is not valid.

但它无效。

回答by Harvey

You can use the following tool to convert and get the code:

您可以使用以下工具进行转换并获取代码:

https://curl.trillworks.com/#node

https://curl.trillworks.com/#node

They support:

他们支持:

  • Node.js
  • Python
  • PHP
  • 节点.js
  • Python
  • PHP

回答by Arian Faurtosh

You are going to need to install the npm module request

您将需要安装 npm 模块请求

If you have npminstalled already, just run the following command:

如果您已经npm安装,只需运行以下命令:

npm install request

Make sure you require the module at the top of your node file, like so

确保您需要节点文件顶部的模块,就像这样

var request = require('request');

You can use the module with the following:

您可以通过以下方式使用该模块:

var request = require('request');

var url = 'https://www.example.com/api/';

var data = {
  "jsonrpc":"2.0",
  "id":"3"
};

request.post({url:url, formData: data}, function(err, httpResponse, body) {
  if (err) {
    return console.error('post failed:', err);
  }

  console.log('Post successful!  Server responded with:', body);
});

Check the documentation out for more information:

查看文档以获取更多信息:

https://www.npmjs.com/package/request

https://www.npmjs.com/package/request

回答by Arul T

You can also do it using postman if you have. (late answer but might help someone else) 1. import curl command into the postman enter image description here

如果有,您也可以使用邮递员来完成。(迟到的答案,但可能会帮助其他人) 1. 将 curl 命令导入邮递员 enter image description here

  1. After import click on the code and you can see many options to generate the code for different languages. enter image description here
  1. 导入后单击代码,您可以看到许多选项来生成不同语言的代码。 enter image description here