cURL equivalent in Node.js?

后端 未结 18 598
误落风尘
误落风尘 2020-11-29 16:43

I\'m looking to use information from an HTTP request using Node.js (i.e. call a remote web service and echo the response to the client).

In PHP I would have used cUR

18条回答
  •  执念已碎
    2020-11-29 16:52

    Uses reqclient, it's a small client module on top of request that allows you to log all the activity with cURL style (optional, for development environments). Also has nice features like URL and parameters parsing, authentication integrations, cache support, etc.

    For example, if you create a client object an do a request:

    var RequestClient = require("reqclient").RequestClient;
    var client = new RequestClient({
            baseUrl:"http://baseurl.com/api/v1.1",
            debugRequest:true, debugResponse:true
        });
    
    var resp = client.post("client/orders", {"client":1234,"ref_id":"A987"}, {headers: {"x-token":"AFF01XX"}})
    

    It will log within the console something like this:

    [Requesting client/orders]-> -X POST http://baseurl.com/api/v1.1/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json
    [Response   client/orders]<- Status 200 - {"orderId": 1320934}
    

    The request will return a Promise object, so you have to handle with then and catch what to do with the result.

    reqclient is available with npm, you can install the module with: npm install reqclient.

提交回复
热议问题