在 Node.js 中发送 HTTP 请求可以使用内置的 httphttps 模块。以下是一个示例:

const http = require('http');

const options = {
  hostname: 'localhost',
  port: 3000,
  path: '/api',
  method: 'GET'
};

const req = http.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', error => {
  console.error(error);
});

req.end();

该示例向 localhost:3000/api 路径发送 GET 请求,并读取响应的数据。可以根据需要修改选项,例如更改请求方法、请求头等。

node 发送HTTP请求

原文地址: https://www.cveoy.top/t/topic/bJBp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录