node和浏览器发送请求的方式

浏览器请求接口运行在客户端的浏览器环境中,而Node请求接口运行在服务器端的Node.js环境中。

浏览器提供了特定的API(如Fetch APIXMLHttpRequest)来发送HTTP请求

fetch:

Fetch API 是一种现代、基于 Promise 的 JavaScript API,用于在浏览器环境中执行网络请求

fetch(url, {  
  method: 'POST', // or 'PUT'  
  headers: {  
    'Content-Type': 'application/json',  
  },  
  body: JSON.stringify(data),  
})  
.then(response => {  
   // 检查响应状态码是否为 200-299  
   if (!response.ok) {  
     throw new Error('Network response was not ok.');  
   }  
   // 解析 JSON 响应体  
   return response.json();  
}) 
.then(data => console.log(data))  
.catch((error) => console.error('Error:', error));

XMLHttpRequest

XMLHttpRequest 提供了丰富的功能,但它的 API 相对复杂,并且错误处理不如 fetch API 直观。因此,在现代 Web 开发中,如果可能的话,建议使用 fetch API。然而,在某些情况下,比如需要更精细地控制请求(例如上传进度、中止请求等),XMLHttpRequest 仍然是一个有用的工具。

var xhr = new XMLHttpRequest();  
xhr.open('POST', 'https://api.example.com/data', true);  
  
// 设置请求头,如果是发送 JSON 数据的话  
xhr.setRequestHeader('Content-Type', 'application/json');  
  
var data = JSON.stringify({ key1: 'value1', key2: 'value2' });  
  
xhr.onload = function () {  
  if (xhr.status === 200) {  
    console.log(xhr.responseText);  
  } else {  
    console.error('Request failed.  Returned status of ' + xhr.status);  
  }  
};  
  
// 发送请求体  
xhr.send(data);

处理请求进度XMLHttpRequest 还提供了处理请求进度事件的功能:

var xhr = new XMLHttpRequest();  
xhr.open('GET', 'https://api.example.com/large-data', true);  
  
xhr.onprogress = function (event) {  
  if (event.lengthComputable) {  
    var percentComplete = (event.loaded / event.total) * 100;  
    console.log(percentComplete + '% 下载完成');  
  }  
};  
  
xhr.onload = function () {  
  if (xhr.status === 200) {  
    console.log(xhr.responseText);  
  } else {  
    console.error('请求失败,状态码:' + xhr.status);  
  }  
};  
  
xhr.send();

Node.js则使用不同的API和工具来发送请求,如http/https模块

http:

在Node.js中,httphttps模块是用于创建HTTP和HTTPS服务器以及发送HTTP和HTTPS请求的。这两个模块提供了底层的HTTP功能,允许你构建基于HTTP协议的客户端和服务器应用。

发送HTTP请求(作为客户端)

const http = require('http');  
  
const options = {  
  hostname: 'www.example.com',  
  port: 80,  
  path: '/todo/api/v1.0/tasks',  
  method: 'GET'  
};  
  
const req = http.request(options, (res) => {  
  let data = '';  
  
  // 当有数据块到来时,追加到data变量  
  res.on('data', (chunk) => {  
    data += chunk;  
  });  
  
  // 当响应完成时,处理数据  
  res.on('end', () => {  
    console.log(JSON.parse(data));  
  });  
});  
  
req.on('error', (error) => {  
  console.error(`问题:${error.message}`);  
});  
  
// 发送请求  
req.end();

创建HTTP服务器

const http = require('http');  
  
const server = http.createServer((req, res) => {  
  res.writeHead(200, {'Content-Type': 'text/plain'});  
  res.end('Hello World\n');  
});  
  
server.listen(8124, () => {  
  console.log('Server running at http://127.0.0.1:8124/');  
});

 

posted @ 2024-03-08 11:08  瑞瑞大人  阅读(25)  评论(0编辑  收藏  举报