📜  http请求正文角度 - Javascript(1)

📅  最后修改于: 2023-12-03 15:15:45.815000             🧑  作者: Mango

HTTP请求正文角度 - JavaScript

简介

在使用 JavaScript 发送 HTTP 请求时,我们需要考虑请求正文的格式和内容。请求正文是指在请求中的主体部分,包含请求参数等信息。本文将介绍使用 JavaScript 发送 HTTP 请求时如何处理请求正文。

XMLHttpRequest

XMLHttpRequest 是发送 AJAX 请求的核心。我们可以通过设置 xhr 对象的属性来指定请求正文的格式和内容。

发送 JSON 请求

如果我们需要向服务器发送 JSON 格式的请求正文,需要将请求正文转换为字符串并设置请求头的 Content-Type 为 application/json。示例代码如下:

const xhr = new XMLHttpRequest();
const url = 'https://example.com/api/users';
const data = { name: 'John', age: 25 };
const json = JSON.stringify(data);

xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/json');

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    const response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};

xhr.send(json);
发送表单数据请求

如果我们需要向服务器发送表单数据格式的请求正文,需要将请求正文转换为熟悉的表单数据格式并设置请求头的 Content-Type 为 application/x-www-form-urlencoded。示例代码如下:

const xhr = new XMLHttpRequest();
const url = 'https://example.com/api/users';
const data = { name: 'John', age: 25 };
const params = new URLSearchParams(data).toString();

xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    const response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};

xhr.send(params);
发送 FormData 请求

如果我们需要向服务器发送带上传文件的请求,需要使用 FormData 对象来处理请求正文。FormData 对象可以自动将表单数据格式转换为 multipart/form-data 格式,同时支持上传文件。示例代码如下:

const xhr = new XMLHttpRequest();
const url = 'https://example.com/api/users';
const data = new FormData();
data.append('name', 'John');
data.append('age', 25);
data.append('avatar', fileInputElement.files[0]);

xhr.open('POST', url);
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    const response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};

xhr.send(data);
fetch

fetch 是一个基于 Promise 的 HTTP 请求库,是 ES6 新引进的特性。通过使用 fetch,可以更加简单方便地发送 HTTP 请求。我们可以使用 Request 对象来设置请求参数,包括请求 URL、请求方法、请求头和请求正文以及响应模式等。示例代码如下:

const url = 'https://example.com/api/users';
const data = { name: 'John', age: 25 };
const json = JSON.stringify(data);

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: json
}).then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
axios

axios 是一个流行的 HTTP 请求库,它支持 Promise API 和拦截器等功能。使用 axios 发送 HTTP 请求时,我们可以通过设置请求信息来指定请求正文的格式和内容。示例代码如下:

const url = 'https://example.com/api/users';
const data = { name: 'John', age: 25 };
const json = JSON.stringify(data);

axios.post(url, json, {
  headers: {
    'Content-Type': 'application/json'
  }
}).then(response => console.log(response.data))
  .catch(error => console.error(error));
结论

使用 JavaScript 发送 HTTP 请求时,需要考虑请求正文的格式和内容。我们可以通过设置 XMLHttpRequest、fetch 或 axios 的请求信息来指定请求正文的格式和内容,包括 JSON、表单数据和 FormData 等。根据实际需求选择合适的请求正文格式和库能够帮助我们更加高效地发送 HTTP 请求。