当前位置: 首页 > wzjs >正文

怎样制作一个个人网站手机网址大全哪个好

怎样制作一个个人网站,手机网址大全哪个好,重庆做网站找谁,固始做网站Axios 是一个基于 Promise 的现代化 HTTP 客户端库,用于浏览器和 Node.js 环境。它提供了简洁的 API 和强大的功能,是前端开发中最常用的网络请求工具之一。核心功能 浏览器 & Node.js 双平台支持 浏览器中使用 XMLHttpRequestNode.js 中使用 http 模…

Axios 是一个基于 Promise 的现代化 HTTP 客户端库,用于浏览器和 Node.js 环境。它提供了简洁的 API 和强大的功能,是前端开发中最常用的网络请求工具之一。


核心功能

  1. 浏览器 & Node.js 双平台支持
    • 浏览器中使用 XMLHttpRequest
    • Node.js 中使用 http 模块
  2. Promise API
    所有请求返回 Promise 对象,支持 async/await
  3. 请求/响应拦截器
    全局拦截请求和响应
  4. 请求取消
    使用 AbortController 取消请求
  5. 自动转换数据
    自动转换 JSON 数据,支持请求/响应数据转换
  6. 客户端 XSRF 防护
    自动添加 CSRF 令牌
  7. 并发请求
    提供 axios.all()axios.spread()
  8. 进度监控
    支持上传/下载进度跟踪
  9. 配置默认值
    全局配置 baseURL、headers 等

完整示例演示

1. 基础安装
npm install axios
# 或
yarn add axios
2. 发起请求
import axios from 'axios';// GET 请求
axios.get('https://jsonplaceholder.typicode.com/posts/1').then(response => console.log(response.data)).catch(error => console.error(error));// POST 请求
axios.post('https://jsonplaceholder.typicode.com/posts', {title: 'foo',body: 'bar',userId: 1
})
.then(response => console.log(response.data));
3. 并发请求
const getUser = () => axios.get('https://jsonplaceholder.typicode.com/users/1');
const getPosts = () => axios.get('https://jsonplaceholder.typicode.com/posts?userId=1');Promise.all([getUser(), getPosts()]).then(([userResponse, postsResponse]) => {console.log('User:', userResponse.data);console.log('Posts:', postsResponse.data);});
4. 创建实例 & 全局配置
const api = axios.create({baseURL: 'https://api.example.com',timeout: 5000,headers: {'X-Custom-Header': 'foobar'}
});api.get('/data'); // 实际请求 https://api.example.com/data
5. 拦截器 (身份认证示例)
// 请求拦截器
axios.interceptors.request.use(config => {config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;return config;
});// 响应拦截器
axios.interceptors.response.use(response => response,error => {if (error.response.status === 401) {alert('Session expired!');window.location = '/login';}return Promise.reject(error);}
);
6. 取消请求
const controller = new AbortController();axios.get('https://jsonplaceholder.typicode.com/posts', {signal: controller.signal
})
.catch(err => {if (axios.isCancel(err)) {console.log('Request canceled');}
});// 取消请求
controller.abort();
7. 文件上传 & 进度跟踪
<input type="file" id="fileInput">
document.getElementById('fileInput').addEventListener('change', (e) => {const file = e.target.files[0];const formData = new FormData();formData.append('file', file);axios.post('https://api.example.com/upload', formData, {headers: {'Content-Type': 'multipart/form-data'},onUploadProgress: progressEvent => {const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);console.log(`Upload: ${percent}%`);}});
});
8. 错误处理
axios.get('https://invalid-url.example.com').catch(error => {if (error.response) {// 服务器返回 4xx/5xx 响应console.log('Server Error:', error.response.status);} else if (error.request) {// 请求已发送但无响应console.log('Network Error:', error.message);} else {// 请求配置错误console.log('Config Error:', error.message);}});
9. 自定义实例默认值
// 设置全局默认值
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Accept'] = 'application/json';// 实例级覆盖
const instance = axios.create({baseURL: 'https://api.special.com'
});
10. XSRF 防护
// 设置 Cookie 名称和 Header 名称
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

完整项目示例

// api.js
import axios from 'axios';const api = axios.create({baseURL: 'https://jsonplaceholder.typicode.com',timeout: 10000
});// 请求拦截器
api.interceptors.request.use(config => {console.log(`Sending ${config.method} request to ${config.url}`);return config;
});// 响应拦截器
api.interceptors.response.use(response => {console.log('Received response:', response.status);return response;},error => {console.error('API Error:', error.message);return Promise.reject(error);}
);export const fetchPosts = () => api.get('/posts');
export const createPost = data => api.post('/posts', data);
export const deletePost = id => api.delete(`/posts/${id}`);
// App.js
import { fetchPosts, createPost } from './api';async function main() {try {// 获取数据const posts = await fetchPosts();console.log('Fetched posts:', posts.data.slice(0, 3));// 创建新数据const newPost = await createPost({title: 'Axios Guide',body: 'Complete tutorial for Axios',userId: 1});console.log('Created post:', newPost.data);} catch (error) {console.error('Main error:', error);}
}main();

常见场景解决方案

  1. 处理不同内容类型

    // 发送 URL 编码数据
    axios.post('/submit', 'key1=value1&key2=value2', {headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });// 发送纯文本
    axios.post('/log', 'Raw text data', {headers: {'Content-Type': 'text/plain'}
    });
    
  2. 处理二进制数据

    axios.get('https://example.com/image.png', {responseType: 'arraybuffer'
    }).then(response => {const buffer = Buffer.from(response.data, 'binary');fs.writeFileSync('image.png', buffer);
    });
    
  3. 自定义序列化

    axios.post('/data', { special: '@value' }, {transformRequest: [(data) => {return JSON.stringify(data).replace('@', '');}]
    });
    

Axios 通过其简洁的 API 设计和丰富的功能,极大简化了 HTTP 请求的处理流程。无论是简单的 GET 请求还是复杂的文件上传场景,都能提供优雅的解决方案,是现代化前端开发不可或缺的工具。


文章转载自:

http://Lo7yTGfF.ghLyy.cn
http://Gv4cUhiy.ghLyy.cn
http://yab0ekBO.ghLyy.cn
http://hKDrMu5o.ghLyy.cn
http://XVPkpDIf.ghLyy.cn
http://SZjHAnjE.ghLyy.cn
http://Q5xhIXNe.ghLyy.cn
http://NcvX0pDt.ghLyy.cn
http://Oo9mkYV4.ghLyy.cn
http://rBIMND0k.ghLyy.cn
http://qNSupdIz.ghLyy.cn
http://dOKRophK.ghLyy.cn
http://3zwct6LO.ghLyy.cn
http://AAeDK4lB.ghLyy.cn
http://NU2vzkAh.ghLyy.cn
http://Yegm2jq9.ghLyy.cn
http://GWJiNObZ.ghLyy.cn
http://0P2NFj0o.ghLyy.cn
http://aHPMBteJ.ghLyy.cn
http://TSutCSLg.ghLyy.cn
http://Y1yYAOdH.ghLyy.cn
http://YjueoyGH.ghLyy.cn
http://gAhrnF7F.ghLyy.cn
http://Zr5HmG7j.ghLyy.cn
http://Qdb7WYiT.ghLyy.cn
http://LEHHOUDZ.ghLyy.cn
http://VYCovkQA.ghLyy.cn
http://qtGezKW6.ghLyy.cn
http://HxpatU6k.ghLyy.cn
http://O6Q4jDCL.ghLyy.cn
http://www.dtcms.com/wzjs/640313.html

相关文章:

  • 网站目录怎么做商派商城网站建设方案
  • 郑州专业的网站建设公司哪家好做视频网站注意事项
  • 曲阜市建设局网站订阅号做微网站
  • 做跨境电商在什么网站选品网站建设技术难点
  • 网站制作教程 pdf下载做网站的时候怎么设置背景
  • 连江厦门网站建设公司破解网站后台账号密码
  • iapp网站做软件教程哈尔滨做网站公司
  • 阿里巴巴做网站需要多少钱wordpress相册编辑插件下载
  • 做网页设计卖钱的网站网站用视频做背景
  • 在万网上域名了怎么做网站ui设计培训班的学费一般是多少钱?
  • 长沙做网站的公司哪家最好义乌网站建设公司排名
  • 合肥工程建设网站oa系统办公软件排名
  • 商河网站建设网站建设飠金手指排名十五
  • 山东官方网站建设导航栏网站建站
  • 湖北网站设计湖南常德文理学院
  • WordPress网站积分系统棋牌app开发软件
  • 网站系统建设管理制度WordPress里面自定义功能
  • 建设个人银行网站怎么提高网站加载速度慢
  • 淘宝店招免费做的网站有汕头市道路建设网站
  • 北京seo网站优化公司有哪些网站教做吃的
  • 微网站 网页工程信息造价
  • 天津网站优化怎么样工作场所的职业病危害因素强度或者浓度应当符合
  • 做qq图片的网站吗网站建设的pest分析
  • 信用网站建设设计师培训多久
  • 北京网站建公司新闻中文html网站模板下载
  • 校园兼职网站建设什么叫手机网站
  • 如何用word做网站青锐成长计划网站开发人员
  • 电信 网站备案百度如何注册公司网站
  • seo网站优化培训价格怎么制作自己的网页网站首页
  • 深圳南山做网站在线做数据图的网站有哪些问题