cURL equivalent in Node.js?

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

    EDIT:

    For new projects please refrain from using request, since now the project is in maitainance mode, and will eventually be deprecated

    https://github.com/request/request/issues/3142

    Instead i would recommend Axios, the library is in line with Node latest standards, and there are some available plugins to enhance it, enabling mock server responses, automatic retries and other features.

    https://github.com/axios/axios

    const axios = require('axios');
    
    // Make a request for a user with a given ID
    axios.get('/user?ID=12345')
      .then(function (response) {
        // handle success
        console.log(response);
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });
    

    Or using async / await:

    try{
        const response = await axios.get('/user?ID=12345');
        console.log(response)
    } catch(axiosErr){
        console.log(axiosErr)
    }
    

    I usually use REQUEST, its a simplified but powerful HTTP client for Node.js

    https://github.com/request/request

    Its on NPM npm install request

    Here is a usage sample:

    var request = require('request');
    
    request('http://www.google.com', function (error, response, body) {
       if (!error && response.statusCode == 200) {
           console.log(body) // Show the HTML for the Google homepage.
       }
    })
    

提交回复
热议问题