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
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
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
2
3
4
5
6
7
8
9
10
11
12
13
上次更新: 2025/10/08, 16:24:59