cURL equivalent in Node.js?

后端 未结 18 592
误落风尘
误落风尘 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: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");
    

提交回复
热议问题