马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本人github
在使用 Axios 进行 HTTP 哀求时,处理响应数据通常遵循以下模式:
根本响应处理
Axios 哀求会返回一个 Promise,该 Promise 解析为一个响应对象。这个响应对象包含了很多有效的信息,好比响应状态码、响应头、以及响应体数据等。
- axios.get('https://api.example.com/data')
- .then(response => {
- console.log(response.data); // 响应体数据
- console.log(response.status); // HTTP 状态码
- console.log(response.headers); // 响应头
- })
- .catch(error => {
- console.error(error);
- });
复制代码 使用 async/await
为了使代码更加简便,你可以使用 async/await 语法来处理 Axios 哀求。这要求将哀求代码放在一个异步函数中。
- async function fetchData() {
- try {
- const response = await axios.get('https://api.example.com/data');
- console.log(response.data); // 响应体数据
- // 可以继续处理 response 对象的其他属性,如 status 和 headers
- } catch (error) {
- console.error(error);
- }
- }
- fetchData();
复制代码 错误处理
Axios 会自动将任何非 2xx 的响应视为错误,并触发 catch 块。在 catch 块中,你可以访问 error 对象来获取错误详情。值得注意的是,error 对象大概包含一个 response 属性,它是当服务器响应时由 Axios 提供的响应对象。
- axios.get('https://api.example.com/data')
- .then(response => {
- console.log(response.data);
- })
- .catch(error => {
- if (error.response) {
- // 请求已发出,服务器以状态码响应不在 2xx 范围内
- console.log(error.response.data);
- console.log(error.response.status);
- console.log(error.response.headers);
- } else if (error.request) {
- // 请求已发出,但未收到响应
- console.log(error.request);
- } else {
- // 在设置请求时发生了某些事情,触发了一个错误
- console.log('Error', error.message);
- }
- });
复制代码 处理超时
你可以在哀求配置中指定 timeout,以毫秒为单位,设置哀求的超时时间。如果哀求超时,Axios 会抛出一个错误。
- axios.get('https://api.example.com/data', { timeout: 5000 }) // 5 秒超时
- .then(response => {
- console.log(response.data);
- })
- .catch(error => {
- console.log('Error', error.message);
- });
复制代码 自定义配置哀求
Axios 答应通过配置对象自定义哀求,包括设置哀求头、参数、超时时间等。
- axios({
- method: 'get',
- url: 'https://api.example.com/data',
- params: {
- key: 'value', // 查询参数
- },
- timeout: 5000, // 5 秒超时
- headers: {
- 'X-Custom-Header': 'value' // 自定义头
- }
- })
- .then(response => {
- console.log(response.data);
- })
- .catch(error => {
- console.log('Error', error.message);
- });
复制代码 总之,使用 Axios 时,通过链式 .then() 和 .catch() 方法或使用 async/await 语法都是处理 HTTP 哀求响应的有效方式。正确的错误处理可以或许让你的应用更加结实和易于维护。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |