Does anyone know how to convert curl commands to n

2019-08-09 16:23发布

I'm stacking on converting curl commands to Node.js for firebase cloud functions. What I referred to "https://curl.trillworks.com/" seems to be not working well. The code is below.

Does anyone know how below code should be written by Node.js?

 curl --include \
     --request POST \
     --header "Content-Type: application/json" \
     --data-binary "{\"app_id\" : \"YOUR_APP_ID\",
\"identifier\":\"DEVICE_VOIP_TOKEN\",
\"language\":\"en\",
\"timezone\":-28800,
\"game_version\":\"1.0\",
\"device_os\":\"7.0.4\",
\"device_type\":0,
\"device_model\":\"iPhone 8,2\",
\"tags\":{\"a\":\"1\",\"foo\":\"bar\"}}" \
     https://onesignal.com/api/v1/players

I'm really thankfully for your help and support.

1条回答
Anthone
2楼-- · 2019-08-09 16:47

the short answer with node request npm package is:

var request = require("request");

var options = { method: 'POST',
    url: 'https://onesignal.com/api/v1/players',
    headers: { 
       'cache-control': 'no-cache',
       'Content-Type': 'application/json' 
   },
   body: { 
     app_id: 'YOUR_APP_ID',
     identifier: 'DEVICE_VOIP_TOKEN',
     language: 'en',
     timezone: -28800,
     game_version: '1.0',
     device_os: '7.0.4',
     device_type: 0,
     device_model: 'iPhone 8,2',
     tags: { a: '1', foo: 'bar' } },
     json: true 
  };

request(options, function (error, response, body) {
 if (error) throw new Error(error);

 console.log(body);
});

Here is some life hack, just give me few minutes and I'll tell you how to translate any curl

[UPDATE] Life hack:
So, there is one app, called Postman. Made by Google. The main goal is to make http requests.
There is a lot of use cases what you can do with Postman but I'll tell about 'translating'.
In Postman header you can find tab "Import"

Postman import


If you click there, you'll see Import tab. Now you're looking for "Paste Raw Text".

Paste Raw Text


Now you should write any curl string to input and press Import.

enter image description here


Then, it will automatically "translate" your curl to request.
Now you're looking for 'code' tab.

enter image description here


You click there and see cUrl example.
Now you have to click on dropdown list

enter image description here


And then select your preferred way to make request

enter image description here


So, now you can translate any curl request to whatever you like.
And, by the way, you can test your post/put/etc. requests with this app.

查看更多
登录 后发表回答