Vue.js 中使用 Axios 发送 HTTP 请求 - 实用示例和指南
在 Vue.js 中使用 Axios 可以用于发送异步网络请求。下面是一些例子:\n\n1. 安装 Axios:在项目中使用 Axios 之前,需要先安装它。在终端中运行以下命令:\n\nnpm install axios\n\n\n2. 导入 Axios:在需要使用 Axios 的组件中,首先需要导入 Axios。\n\nimport axios from 'axios';\n\n\n3. 发送 GET 请求:\n\naxios.get('/api/data')\n .then(response => {\n console.log(response.data);\n })\n .catch(error => {\n console.error(error);\n });\n\n\n4. 发送 POST 请求:\n\naxios.post('/api/data', {name: 'John', age: 25})\n .then(response => {\n console.log(response.data);\n })\n .catch(error => {\n console.error(error);\n });\n\n\n5. 设置请求 header:\n\naxios.get('/api/data', {\n headers: {\n 'Authorization': 'Bearer token123'\n }\n})\n .then(response => {\n console.log(response.data);\n })\n .catch(error => {\n console.error(error);\n });\n\n\n6. 并行请求:\n\naxios.all([\n axios.get('/api/data1'),\n axios.get('/api/data2')\n])\n .then(axios.spread((response1, response2) => {\n console.log(response1.data);\n console.log(response2.data);\n }))\n .catch(error => {\n console.error(error);\n });\n\n\n以上是一些基本的 Axios 用法例子。根据实际需求,还可以使用 Axios 的其他功能,如拦截器、取消请求等。
原文地址: https://www.cveoy.top/t/topic/qAbr 著作权归作者所有。请勿转载和采集!