如何从客户端发起JSON请求:全面指南
在Web开发中,客户端(如浏览器、移动端App)与服务器之间的数据交互是核心环节,JSON(JavaScript Object Notation)因其轻量级、易读、易于机器解析的特性,已成为前后端数据交换的主流格式,本文将详细介绍如何从客户端发起JSON请求,涵盖常见场景(如Ajax、Fetch API)、具体代码示例、关键注意事项及跨域解决方案,助你这一核心技能。
发起JSON请求的核心步骤
无论使用哪种技术栈,从客户端发起JSON请求通常包含以下核心步骤:
- 确定请求目标:明确服务器的API接口URL(如
https://api.example.com/data)。 - 设置请求方法:根据业务需求选择GET(查询)、POST(创建)、PUT(更新)、DELETE(删除)等HTTP方法。
- 配置请求头:告知服务器请求体的数据格式为JSON(通常设置
Content-Type: application/json)。 - 构造请求体:将数据转换为JSON字符串(POST/PUT请求常用)。
- 发送请求并处理响应:通过客户端API发送请求,并在回调中解析服务器返回的JSON数据。
常见客户端发起JSON请求的方式
使用Fetch API(现代浏览器推荐)
Fetch API是现代浏览器内置的HTTP请求接口,基于Promise设计,语法简洁,支持异步操作,是目前前端发起请求的主流方式。
基本语法
fetch(url, options)
.then(response => response.json()) // 解析响应体为JSON
.then(data => console.log(data))
.catch(error => console.error('请求失败:', error));
示例:POST请求发送JSON数据
// 1. 定义请求数据(JavaScript对象)
const requestData = {
name: "张三",
age: 25,
email: "zhangsan@example.com"
};
// 2. 发起POST请求
fetch('https://api.example.com/users', {
method: 'POST', // 请求方法
headers: {
'Content-Type': 'application/json', // 告知服务器请求体是JSON
'Authorization': 'Bearer your_token' // 可选:认证信息
},
body: JSON.stringify(requestData) // 将对象转为JSON字符串
})
.then(response => {
if (!response.ok) { // 检查HTTP状态码
throw new Error(`HTTP错误! 状态码: ${response.status}`);
}
return response.json(); // 解析响应数据
})
.then(data => {
console.log('服务器返回:', data);
// 处理返回的数据(如更新页面UI)
})
.catch(error => {
console.error('请求出错:', error);
});
GET请求示例(无需请求体)
fetch('https://api.example.com/users?name=张三', {
method: 'GET',
headers: {
'Accept': 'application/json' // 告知服务器期望返回JSON
}
})
.then(response => response.json())
.then(data => console.log(data));
Fetch API特点
- 优点:基于Promise,避免回调地狱;支持流式响应;语法简洁。
- 缺点:默认不发送跨域Cookie(需设置
credentials: 'include');错误处理需手动检查HTTP状态码(如404、500不会触发Promise的catch)。
使用XMLHttpRequest(传统方式)
XMLHttpRequest(XHR)是早期浏览器支持的HTTP请求对象,是Ajax技术的核心,虽然Fetch API已逐渐取代它,但在部分旧项目或需兼容IE9以下浏览器时仍会使用。
基本语法
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/users');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send(JSON.stringify(requestData));
完整示例
const requestData = { name: "李四", age: 30 };
const xhr = new XMLHttpRequest();
// 初始化请求
xhr.open('POST', 'https://api.example.com/users', true);
// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/json');
// 监听请求状态变化
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // 请求完成
if (xhr.status === 200) { // 成功
try {
const data = JSON.parse(xhr.responseText);
console.log('成功:', data);
} catch (error) {
console.error('JSON解析失败:', error);
}
} else { // 失败
console.error('请求失败,状态码:', xhr.status);
}
}
};
// 发送请求(需将对象转为JSON字符串)
xhr.send(JSON.stringify(requestData));
XMLHttpRequest特点
- 优点:兼容性极好(支持IE7+);可上传/下载文件;支持进度监控。
- 缺点:基于回调,代码嵌套复杂;API设计不够直观(如需手动管理readyState)。
使用第三方库(如Axios)
Axios是一个基于Promise的HTTP客户端,支持浏览器和Node.js,封装了Fetch API和XMLHttpRequest,提供了更简洁的API和更强大的功能(如请求/响应拦截、自动JSON转换、超时处理等)。
安装
npm install axios # 或CDN引入 <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
示例:POST请求发送JSON
const requestData = { name: "王五", age: 28 };
axios.post('https://api.example.com/users', requestData, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token'
},
timeout: 5000 // 超时时间(毫秒)
})
.then(response => {
console.log('服务器返回:', response.data);
// Axios会自动解析JSON,response.data直接是对象
})
.catch(error => {
if (error.response) {
// 服务器返回了错误状态码(4xx/5xx)
console.error('服务器错误:', error.response.status, error.response.data);
} else if (error.request) {
// 请求已发送但无响应(如网络断开)
console.error('无响应:', error.request);
} else {
// 请求配置错误
console.error('请求错误:', error.message);
}
});
GET请求示例
axios.get('https://api.example.com/users', {
params: { name: "王五" }, // 自动将参数拼接到URL?后
headers: { 'Accept': 'application/json' }
})
.then(response => console.log(response.data));
Axios特点
- 优点:自动JSON序列化/反序列化;支持请求/响应拦截器;支持并发请求(
axios.all);更好的错误处理;支持浏览器和Node.js。 - 缺点:需额外引入库(体积约5KB,但可通过按需引入优化)。
移动端(如React Native、Flutter)
在移动端开发中,发起JSON请求的逻辑与Web端类似,但需使用平台特定的HTTP客户端。
React Native示例(使用fetch)
import React, { useState, useEffect } from 'react';
const App = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
},
})
.then(response => response.json())
.then(json => setData(json))
.catch(error => console.error(error));
}, []);
return (
<div>
{data ? <pre>{JSON.stringify(data, null, 2)}</pre> : <p>加载中...</p>}
</div>
);
};
export default App;
Flutter示例(使用http包)
-
添加依赖到
pubspec.yaml:dependencies: http: ^1.1.0
-
发起请求:
import 'dart:convert'; import 'package:http/http.dart' as http;
Future<void fetchData() async { final url = Uri.parse('https://api.example.com/data'); try { final response = await http.get( url, headers: {'Accept': 'application/json'}, ); if (response.statusCode == 200) { final data = json.decode(response.body); print('服务器返回: $data'); } else { print('请求失败,状态码: ${response.statusCode}'); } } catch (error) { print('请求出错: $error'); } }
## 三、关键注意事项
### 1. 请求头(Headers)必须正确设置
- **`Content-Type: application/json`**:当请求体为JSON时,需通过此头告知服务器,否则服务器可能无法正确解析数据


还没有评论,来说两句吧...