x-www-form-urlencoded 是一种 MIME 类型,用于表示键值对编码的表单数据。它通常用于 HTTP 请求的 POST 方法,将表单数据编码为 URL 编码格式,并作为请求体发送到服务器。
编码规则
- 键值对以
&分隔。 - 每个键和值使用
=分隔。 - 特殊字符(如空格、&、= 等)会被 URL 编码,例如空格编码为
+或%20。
示例
假设有以下表单数据:
name=John Doe
age=30
city=New York
编码后的 x-www-form-urlencoded 数据如下:
name=John+Doe&age=30&city=New+York
使用示例
使用 XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/submit', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = 'name=John+Doe&age=30&city=New+York';
xhr.send(data);
使用 fetch
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'name=John+Doe&age=30&city=New+York'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
使用 FormData 对象
可以使用 FormData 对象来构建表单数据,然后将其转换为 x-www-form-urlencoded 格式。
var formData = new FormData();
formData.append('name', 'John Doe');
formData.append('age', '30');
formData.append('city', 'New York');
var urlEncodedData = new URLSearchParams(formData).toString();
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: urlEncodedData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
服务器端解析
在服务器端,可以解析 x-www-form-urlencoded 数据。例如,在 Node.js 中可以使用 body-parser 中间件来解析请求体。
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/submit', (req, res) => {
console.log(req.body);
res.send('Data received');
});
app.listen(3000, () => console.log('Server running on port 3000'));