浏览器在向服务器发送请求时,可以在请求体(request body)中包含多种类型的数据。这些数据通常用于POST、PUT等HTTP方法,以提交表单数据、文件上传、JSON对象等。下面是一些常见的数据格式:
1. 表单数据 (application/x-www-form-urlencoded)
- 这是最常见的格式,用于发送键值对形式的数据。
- 键值对之间用
&
分隔,键和值之间用=
连接。 - 值会被URL编码(例如空格变成
+
)。
前端请求
POST /url HTTP/1.1
Host: localhost:8080
User-Agent: Apifox/1.0.0 (https://apifox.com)
Accept: */*
Host: localhost:8080
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
id=1&name=whales&status=OK
后端接收 方式一 使用 @RequestParam
//当方法参数名与请求参数名不同时,必须使用 @RequestParam 注解来显式地指定参数名。
//如果请求参数名与方法参数名相同,但你想指定默认值或是否必需等属性,仍然需要使用 @RequestParam 注解。
@PostMapping("/url")
public Map<String, Object> getURL(@RequestParam String id,
@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "status", required = false, defaultValue = "0") String status) {
return Map.of("id", id, "name", name, "status", status);
}
// 如果请求参数的名称与控制器方法中的参数名称完全相同,则可以省略 @RequestParam 注解。Spring 会自动尝试将这些参数进行绑定。
@PostMapping("/url")
public Map<String,Object> getURL(String id, String name, String status) {
return Map.of("id",id,"name",name,"status",status);
}
后端接收 方式二 使用 HttpServletRequest
@PostMapping("/url")
public Map<String, Object> getURL2(HttpServletRequest request) {
String id = request.getParameter("id");
String name = request.getParameter("name");
String status = request.getParameter("status");
return Map.of("id", id, "name", name, "status", status);
}
后端接收 方式三使用 使用 POJO 类
@PostMapping("/url")
public Map<String, Object> getURL3(Student student) {
int id = student.getId();
String name = student.getName();
String status = student.getStatus();
return Map.of("id", id, "name", name, "status", status);
}
// @ModelAttribute 是 Spring MVC 框架中的一个注解,用于处理控制器方法中的参数绑定。它主要用来简化模型数据的管理和传递。
@PostMapping("/url")
public Map<String, Object> getURL3(@ModelAttribute Student student) {
int id = student.getId();
String name = student.getName();
String status = student.getStatus();
return Map.of("id", id, "name", name, "status", status);
}
后端接收 方式四 使用 @RequestBody 结合 MultiValueMap PUT 错误请求
@PostMapping("/url")
public Map<String, String> getURL4(@RequestBody MultiValueMap<String, String> reqMap) {
Map<String, String> map = reqMap.toSingleValueMap();
return map;
}
2. JSON 数据 (application/json)
- JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。
- JSON数据可以是简单的键值对,也可以是嵌套的对象和数组。
- 浏览器需要先将JavaScript对象转换成JSON字符串,然后再发送。
POST /url HTTP/1.1
Host: localhost:8080
User-Agent: Apifox/1.0.0 (https://apifox.com)
Content-Type: application/json
Accept: */*
Host: localhost:8080
Connection: keep-alive
{
"id": "79",
"name": "放展比说近许",
"status": "laboris"
}
后端接收
@PostMapping("/json")
public Map<String, Object> getJSON2(@RequestBody Student student) {
int id = student.getId();
String name = student.getName();
String status = student.getStatus();
return Map.of("id", id, "name", name, "status", status);
}
-
XML 数据 (application/xml)
- XML(Extensible Markup Language)是一种用于标记数据的标准。
- 虽然XML不如JSON流行,但在某些领域仍然被广泛使用,比如SOAP协议。
-
多部分/文件上传 (multipart/form-data)
- 当需要上传文件时,通常会使用这种格式。
- 它允许同时发送文件和其他表单数据。
- 每个部分都由边界字符串(boundary)分隔。
使用 @RequestParam 和 MultipartFile
-
二进制数据 (application/octet-stream)
- 用于发送未解释的二进制数据,如图像、音频文件等。
- 这种格式通常用于特定的应用程序,比如上传文件。
-
纯文本 (text/plain)
- 发送纯文本数据,如简单的文本消息或日志条目。
- 不会进行特殊的编码处理。
-
自定义格式
- 开发者还可以定义自己的媒体类型,并在请求头中指定。
- 这种情况相对较少见,主要用于特定的应用场景。
为了确保服务器能够正确解析请求体中的数据,你需要在HTTP请求头中设置Content-Type
来指示所发送数据的类型。例如,发送JSON数据时,应该设置Content-Type: application/json
。
这里是一个使用JSON格式的例子:
fetch('https://example.com/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
key: 'value',
anotherKey: 42
})
});
Axios请求配置
这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 GET 方法。
{
// `url` 是用于请求的服务器 URL
url: '/user',
// `method` 是创建请求时使用的方法
method: 'get', // 默认值
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
// 你可以修改请求头。
transformRequest: [function (data, headers) {
// 对发送的 data 进行任意转换处理
return data;
}],
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对接收的 data 进行任意转换处理
return data;
}],
// 自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是与请求一起发送的 URL 参数
// 必须是一个简单对象或 URLSearchParams 对象
params: {
ID: 12345
},
// `paramsSerializer`是可选方法,主要用于序列化`params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` 是作为请求体被发送的数据
// 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
// 在没有设置 `transformRequest` 时,则必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属: FormData, File, Blob
// - Node 专属: Stream, Buffer
data: {
firstName: 'Fred'
},
// 发送请求体数据的可选语法
// 请求方式 post
// 只有 value 会被发送,key 则不会
data: 'Country=Brasil&City=Belo Horizonte',
// `timeout` 指定请求超时的毫秒数。
// 如果请求时间超过 `timeout` 的值,则请求会被中断
timeout: 1000, // 默认值是 `0` (永不超时)
// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default
// `adapter` 允许自定义处理请求,这使测试更加容易。
// 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
adapter: function (config) {
/* ... */
},
// `auth` HTTP Basic Auth
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示浏览器将要响应的数据类型
// 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
// 浏览器专属:'blob'
responseType: 'json', // 默认值
// `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
// 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // 默认值
// `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
xsrfCookieName: 'XSRF-TOKEN', // 默认值
// `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
// `onUploadProgress` 允许为上传处理进度事件
// 浏览器专属
onUploadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `onDownloadProgress` 允许为下载处理进度事件
// 浏览器专属
onDownloadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
maxContentLength: 2000,
// `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
maxBodyLength: 2000,
// `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
// 则promise 将会 resolved,否则是 rejected。
validateStatus: function (status) {
return status >= 200 && status < 300; // 默认值
},
// `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
// 如果设置为0,则不会进行重定向
maxRedirects: 5, // 默认值
// `socketPath` 定义了在node.js中使用的UNIX套接字。
// e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
// 只能指定 `socketPath` 或 `proxy` 。
// 若都指定,这使用 `socketPath` 。
socketPath: null, // default
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
// and https requests, respectively, in node.js. This allows options to be added like
// `keepAlive` that are not enabled by default.
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` 定义了代理服务器的主机名,端口和协议。
// 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
// 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
// `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
// 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
// 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// see https://axios-http.com/zh/docs/cancellation
cancelToken: new CancelToken(function (cancel) {
}),
// `decompress` indicates whether or not the response body should be decompressed
// automatically. If set to `true` will also remove the 'content-encoding' header
// from the responses objects of all decompressed responses
// - Node only (XHR cannot turn off decompression)
decompress: true // 默认值
}
import axios from 'axios'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import router from '@/router'
//创建axios的实例
const instance = axios.create({
baseURL: 'http://localhost:8000/boss',
timeout: 5000
})
//get请求,url传参
function doGet(path, parameters) {
return instance({
url: path,
method: 'GET',
params: parameters
})
}
//封装post请求,传递json数据
function doPostJson(path, parameters) {
return instance({
url: path,
method: 'POST',
data: parameters
})
}
//封装post请求,传递name=value数据 , { 'age':20, 'sex':'m'} --- age=20&sex=m
function doPostForm(path, parameters) {
return instance({
url: path,
method: 'POST',
data: qs.stringify(parameters)
})
}
//请求拦截器
instance.interceptors.request.use(
(config) => {
//增加jwt的请求header
const sessionString = sessionStorage.getItem('BOSS_TOKEN')
if (sessionString) {
let sessionObject = JSON.parse(sessionString)
config.headers.Authorization = 'Bearer ' + sessionObject.jwt
config.headers.operatorId = sessionObject.operatorId
}
return config
},
(err) => {
console.log('请求拦截器错误:' + err)
}
)
export { doGet, doPostJson, doPostForm }