Jacky's blog
首页
  • Android
  • Web
  • Server
  • Python
  • iOS
  • Java
  • Vue
  • 计算机基础
  • AI
  • 全部工具
  • CLI 工具
  • 编辑器
  • 开发工具
  • 构建工具
  • 版本控制
  • 调试工具
  • 网络工具
  • 个人成长
  • 博客
  • 分类
  • 标签
  • 归档
收藏
GitHub (opens new window)

Jack Yang

编程; 随笔
首页
  • Android
  • Web
  • Server
  • Python
  • iOS
  • Java
  • Vue
  • 计算机基础
  • AI
  • 全部工具
  • CLI 工具
  • 编辑器
  • 开发工具
  • 构建工具
  • 版本控制
  • 调试工具
  • 网络工具
  • 个人成长
  • 博客
  • 分类
  • 标签
  • 归档
收藏
GitHub (opens new window)
  • web
  • 工具

  • JavaScript

  • CSS

  • Vue

  • React

  • Next.js

  • 模块化

  • web faq
  • Web3

  • 更多

    • typescript
    • 批量打开网站
    • 启动express服务
    • nodejs中的http请求
      • 使用 axios
      • 使用 http/https 模块
      • 浏览器的 http 请求
    • blob url
    • php
    • prettier
    • electron
    • animation
    • 一行代码"黑"掉任意网站
    • Atom 状态管理
  • web concept
  • web
  • more
Jacky
2024-05-23
目录

nodejs中的http请求

在 Node.js 中,你可以使用 axios 或内置的 http/https 模块来发送 HTTP 请求。如果你不想创建 package.json 文件,可以直接在 Node.js shell 中使用 require 来加载模块并发送请求

# 使用 axios

axios 是一个基于 Promise 的 HTTP 客户端,可以用于浏览器和 Node.js。你需要先安装它。即使你没有 package.json 文件,也可以在命令行中全局安装 axios,然后在 Node.js shell 中使用它

1.安装 axios:npm install -g axios

2.在 Node.js shell 中使用 axios:

const axios = require('axios');

axios
    .get('https://api.example.com')
    .then((response) => {
        console.log(response.data);
    })
    .catch((error) => {
        console.error(error);
    });
1
2
3
4
5
6
7
8
9
10

# 使用 http/https 模块

Node.js 内置的 http 和 https 模块也可以用于发送 HTTP 请求。这种方法不需要安装额外的模块

const https = require('https');

https
    .get('https://api.example.com', (resp) => {
        let data = '';

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

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log(JSON.parse(data));
        });
    })
    .on('error', (err) => {
        console.log('Error: ' + err.message);
    });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

这两种方法都可以在 Node.js shell 中直接运行,具体取决于你是否愿意安装额外的模块。使用 axios 会更加简洁和现代化,而使用 http/https 模块则不需要额外的安装步骤

# 浏览器的 http 请求

在浏览器的控制台中,你可以使用 XMLHttpRequest 或现代的 fetch API 来发送 HTTP 请求

fetch('https://api.example.com')
    .then((response) => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json(); // Assuming the response is in JSON format
    })
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error('There was a problem with the fetch operation:', error);
    });
1
2
3
4
5
6
7
8
9
10
11
12
13
#Node.js#Web
上次更新: 2026/10/18, 22:14:48
启动express服务
blob url

← 启动express服务 blob url→

最近更新
01
Codex 使用与会话管理指南
10-17
02
Tailscale 入门:让自己的设备跨网络互联
10-15
03
GitHub CLI(gh)工作流与 CI 排查
10-08
更多文章>
Theme by Vdoing | Copyright © 2019-2026 Jacky | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式