在Node.js Express中进行HTTP GET请求

228

我该如何在Node.js或Express.js中发起HTTP请求?我需要连接到另一个服务。希望这个调用是异步的,回调函数包含远程服务器的响应。


在 Node.js 18 中,默认情况下在全局范围内提供了 fetch API。 - Abolfazl Roshanzamir
13个回答

0
如果您需要向IP和域名(其他答案未提到您可以指定端口变量)发送GET请求,您可以使用以下函数:
``` def send_get_request(ip, domain, port=80): url = f"http://{ip}:{port}/{domain}" response = requests.get(url) return response ```
function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

不要忘记在文件顶部引入所需的模块:
http = require("http");
url = require('url')

请注意,您可以使用https模块进行安全网络通信。因此,以下这两行代码会发生改变:
https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......

0

使用reqclient: 不适合脚本化的目的,例如request或许多其他库。Reqclient允许在构造函数中指定许多配置,当您需要重复使用相同的配置时非常有用:基础URL、标头、身份验证选项、日志记录选项、缓存等。还具有实用功能,如查询和URL解析、自动查询编码和JSON解析等。

最好的方法是创建一个模块来导出指向API的对象和连接所需的必要配置:

模块client.js

let RequestClient = require("reqclient").RequestClient

let client = new RequestClient({
  baseUrl: "https://myapp.com/api/v1",
  cache: true,
  auth: {user: "admin", pass: "secret"}
})

module.exports = client

在需要使用 API 的控制器中,可以像这样使用:

let client = require('client')
//let router = ...

router.get('/dashboard', (req, res) => {
  // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
  client.get("reports/clients")
    .then(response => {
       console.log("Report for client", response.userId)  // REST responses are parsed as JSON objects
       res.render('clients/dashboard', {title: 'Customer Report', report: response})
    })
    .catch(err => {
      console.error("Ups!", err)
      res.status(400).render('error', {error: err})
    })
})

router.get('/orders', (req, res, next) => {
  // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
  client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
    .then(orders => {
      res.render('clients/orders', {title: 'Customer Orders', orders: orders})
    })
    .catch(err => someErrorHandler(req, res, next))
})

router.delete('/orders', (req, res, next) => {
  // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
  client.delete({
    "uri": "orders/{client}/{id}",
    "params": {"client": "A987", "id": 1234}
  })
  .then(resp => res.status(204))
  .catch(err => someErrorHandler(req, res, next))
})

reqclient 支持许多功能,但它具有其他库不支持的一些功能:OAuth2 集成和与 cURL 语法 的日志记录器集成,并始终返回本机 Promise 对象。


-1
## you can use request module and promise in express to make any request ##
const promise                       = require('promise');
const requestModule                 = require('request');

const curlRequest =(requestOption) =>{
    return new Promise((resolve, reject)=> {
        requestModule(requestOption, (error, response, body) => {
            try {
                if (error) {
                    throw error;
                }
                if (body) {

                    try {
                        body = (body) ? JSON.parse(body) : body;
                        resolve(body);
                    }catch(error){
                        resolve(body);
                    }

                } else {

                    throw new Error('something wrong');
                }
            } catch (error) {

                reject(error);
            }
        })
    })
};

const option = {
    url : uri,
    method : "GET",
    headers : {

    }
};


curlRequest(option).then((data)=>{
}).catch((err)=>{
})

正如事实所示,这并不能解决问题。这段代码将会“监听请求”,但问题是要求如何“发送请求”。 - Quentin
1
这是固定的,你可以试一下。@Quentin - izhar ahmad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接