Ilshat
Ilshat

Reputation: 196

Convert cURL request to request of node.js

Here is my valid cURL command:

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

here is what I tried in 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.

Upvotes: 8

Views: 29886

Answers (4)

Deepak
Deepak

Reputation: 2727

If you want to programatically generate nodejs code from curl then try httpsnippet by Kong.

httpsnippet support lots of languages and is being actively maintained by Kong.

HTTP Request snippet generator for many languages & tools including: cURL, HTTPie, Javascript, Node, C, Java, PHP, Objective-C, Swift, Python, Ruby, C#, Go, OCaml and more!

Upvotes: 0

AD14
AD14

Reputation: 1218

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. After import click on the code and you can see many options to generate the code for different languages. enter image description here

Upvotes: 13

Harshal Yeole
Harshal Yeole

Reputation: 4993

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

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

They support:

  • Node.js
  • Python
  • PHP

Upvotes: 16

Arian Faurtosh
Arian Faurtosh

Reputation: 18521

You are going to need to install the npm module request

If you have npm installed already, just run the following command:

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

Upvotes: 5

Related Questions