Does anyone know how to convert curl commands to node.js for firebase cloud functions

荒凉一梦 提交于 2019-12-11 05:22:26

问题


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:


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"


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


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


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


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


And then select your preferred way to make request


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.



来源:https://stackoverflow.com/questions/54147389/does-anyone-know-how-to-convert-curl-commands-to-node-js-for-firebase-cloud-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!