前端 JS 经典:Content-type 详解
warning:
这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
在前端JavaScript中,Content-type是HTTP请求头中的一部分,它用于指定发送数据的类型。常见的Content-type类型有:application/json、application/x-www-form-urlencoded、multipart/form-data等。
application/json:这是发送JSON格式数据的首选类型。JavaScript中,可以使用JSON.stringify()将对象转换为JSON字符串。
let data = JSON.stringify({
name: 'John',
age: 30
});
fetch('https://example.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
});application/x-www-form-urlencoded:这种类型通常用于发送表单数据。可以使用URLSearchParams对象来构建这种格式的数据。
let params = new URLSearchParams();
params.append('name', 'John');
params.append('age', '30');
fetch('https://example.com', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params.toString()
});multipart/form-data:这种类型用于发送包含文件上传的表单数据。需要使用FormData对象。
let formData = new FormData();
formData.append('name', 'John');
formData.append('age', '30');
let file = document.querySelector('input[type="file"]').files[0];
formData.append('file', file);
fetch('https://example.com', {
method: 'POST',
body: formData
}); // 不需要显式设置Content-Type,因为FormData自动处理根据你的需求选择合适的Content-type类型,并在发送请求时设置正确的头部。
评论已关闭