cURL equivalent in Node.js?

后端 未结 18 603
误落风尘
误落风尘 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:51

    You can try using POSTMAN Chrome app for your request and you can generate node js code from there

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 16:53

    The above examples work but don't go so far as to really deal with a real world example (i.e. when you process data coming in multiple chunks. One thing you need to make sure of is that you have an 'on chunk' handler that push's the data into an array (fastest way to do this in JS) and an 'on end' handler that joins them all together so you can return it.

    This is especially necessary when you're working with big requests (5000+ lines) and the server sends a bunch of data at you.

    Here's an example in one of my programs (coffeescript): https://gist.github.com/1105888

    0 讨论(0)
  • 2020-11-29 16:54

    Here is a standard lib (http) async / await solution.

    const http = require("http");
    
    const fetch = async (url) => {
      return new Promise((resolve, reject) => {
        http
          .get(url, (resp) => {
            let data = "";
            resp.on("data", (chunk) => {
              data += chunk;
            });
            resp.on("end", () => {
              resolve(data);
            });
          })
          .on("error", (err) => {
            reject(err);
          });
      });
    };
    

    Usage:

    await fetch("http://example.com");
    
    0 讨论(0)
  • 2020-11-29 16:55

    Since looks like node-curl is dead, I've forked it, renamed, and modified to be more curl like and to compile under Windows.

    node-libcurl

    Usage example:

    var Curl = require( 'node-libcurl' ).Curl;
    
    var curl = new Curl();
    
    curl.setOpt( Curl.option.URL, 'www.google.com' );
    curl.setOpt( 'FOLLOWLOCATION', true );
    
    curl.on( 'end', function( statusCode, body, headers ) {
    
        console.info( statusCode );
        console.info( '---' );
        console.info( body.length );
        console.info( '---' );
        console.info( headers );
        console.info( '---' );
        console.info( this.getInfo( Curl.info.TOTAL_TIME ) );
    
        this.close();
    });
    
    curl.on( 'error', function( err, curlErrorCode ) {
    
        console.error( err.message );
        console.error( '---' );
        console.error( curlErrorCode );
    
        this.close();
    
    });
    
    curl.perform();
    

    Perform is async, and there is no way to use it synchronous currently (and probably will never have).

    It's still in alpha, but this is going to change soon, and help is appreciated.

    Now it's possible to use Easy handle directly for sync requests, example:

    var Easy = require( 'node-libcurl' ).Easy,
        Curl = require( 'node-libcurl' ).Curl,
        url = process.argv[2] || 'http://www.google.com',
        ret, ch;
    
    ch = new Easy();
    
    ch.setOpt( Curl.option.URL, url );
    
    ch.setOpt( Curl.option.HEADERFUNCTION, function( buf, size, nmemb ) {
    
        console.log( buf );
    
        return size * nmemb;
    });
    
    ch.setOpt( Curl.option.WRITEFUNCTION, function( buf, size, nmemb ) {
    
        console.log( arguments );
    
        return size * nmemb;
    });
    
    // this call is sync!
    ret = ch.perform();
    
    ch.close();
    
    console.log( ret, ret == Curl.code.CURLE_OK, Easy.strError( ret ) );
    

    Also, the project is stable now!

    0 讨论(0)
  • 2020-11-29 16:58

    There is npm module to make a curl like request, npm curlrequest.

    Step 1: $npm i -S curlrequest

    Step 2: In your node file

    let curl = require('curlrequest')
    let options = {} // url, method, data, timeout,data, etc can be passed as options 
    curl.request(options,(err,response)=>{
    // err is the error returned  from the api
    // response contains the data returned from the api
    })
    

    For further reading and understanding, npm curlrequest

    0 讨论(0)
提交回复
热议问题