Node.js 中发送 GET 请求可以通过多种方式实现,其中最常用的库是 axios
和 Node.js 内置的 http
或 https
模块。以下是使用这些方法发送 GET 请求的基础概念、优势、类型、应用场景以及示例代码。
axios
发送 GET 请求首先,需要安装 axios
:
npm install axios
然后,使用以下代码发送 GET 请求:
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
http
模块发送 GET 请求const http = require('http');
const options = {
hostname: 'api.example.com',
port: 80,
path: '/data',
method: 'GET'
};
const req = http.request(options, res => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
console.log(JSON.parse(data));
});
});
req.on('error', error => {
console.error('Error:', error);
});
req.end();
https
模块发送 GET 请求(适用于 HTTPS 网站)const https = require('https');
const options = {
hostname: 'api.example.com',
port: 443,
path: '/data',
method: 'GET'
};
const req = https.request(options, res => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
console.log(JSON.parse(data));
});
});
req.on('error', error => {
console.error('Error:', error);
});
req.end();
原因:浏览器的同源策略限制了不同源之间的请求。 解决方法:
Access-Control-Allow-Origin
头。原因:网络延迟或服务器响应慢。 解决方法:
原因:网络错误、服务器错误等。 解决方法:
.catch()
或 try-catch
捕获并处理错误。通过以上方法和示例代码,可以有效地在 Node.js 中发送 GET 请求并处理常见问题。
领取专属 10元无门槛券
手把手带您无忧上云