Jacky's blog
首页
  • 学习笔记

    • web
    • android
    • iOS
    • vue
  • 分类
  • 标签
  • 归档
收藏
  • tool
  • algo
  • python
  • java
  • server
  • growth
  • frida
  • blog
  • SP
  • more
GitHub (opens new window)

Jack Yang

编程; 随笔
首页
  • 学习笔记

    • web
    • android
    • iOS
    • vue
  • 分类
  • 标签
  • 归档
收藏
  • tool
  • algo
  • python
  • java
  • server
  • growth
  • frida
  • blog
  • SP
  • more
GitHub (opens new window)
  • web
  • web concept
  • javascript

  • css

  • vue

  • react

  • nextjs

  • module

  • web faq
  • web3

  • more

    • 一行代码"黑"掉任意网站
    • 批量打开网站
    • 启动express服务
    • nodejs中的http请求
      • 使用 axios
      • 使用 http/https 模块
      • 浏览器的 http 请求
    • blob url
    • php
    • session and cookie
    • prettier
  • 《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
上次更新: 2025/10/08, 16:24:59
启动express服务
blob url

← 启动express服务 blob url→

最近更新
01
npx 使用指南
10-12
02
cursor
09-28
03
inspect
07-20
更多文章>
Theme by Vdoing | Copyright © 2019-2025 Jacky | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式