axios 详细使用方法 及跨域请求(反向代理)的处理

本文介绍如何使用Axios发起HTTP请求。包括通过npm、bower安装Axios,或使用CDN方式引入;设置Vue原型以便全局访问;配置Webpack代理;演示GET、POST请求及并发请求的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装


使用 npm:

$ npm install axios
  • 1

或者 使用 bower:

$ bower install axios
  • 1

或者直接使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  • 1

main.js设置如下

引入axios

import axios from 'axios'
  • 1

挂载到vue的原型

Vue.prototype.$http = axios
  • 1

在webpack.config.js(config—>index.js)文件里设置代理

dev: {
    env: require('./dev.env'),
    port: 8080,  //设置访问的端口号
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/api': {
            target: 'http://10.10:8063', //设置调用接口域名和端口号别忘了加http
            changeOrigin: true,
            pathRewrite: {
                '^/api': '/' //这里理解成用‘/api’代替target里面的地址,组件中我们调接口时直接用/api代替
                    // 比如我要调用'http://0.0:300/user/add',直接写‘/api/user/add’即可 代理后地址栏显示/
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

执行 GET 请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

执行 POST 请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

执行多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

创建实例
可以使用自定义配置新建一个 axios 实例
axios.create([config])

var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
  • 1
  • 2
  • 3
  • 4
  • 5

在前端使用axios发送请求时出现CORS(资源共享)错误,通常是由于浏览器的同源策略限制导致的。要解决这个问题,可以从以下几个方面入手: 1. **服务器端设置CORS头**: 确保服务器端配置了正确的CORS头,以允许特定来源的请求。例如,在Node.js的Express框架中,可以使用`cors`中间件: ```javascript const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors({ origin: 'http://your-frontend-domain.com', methods: ['GET', 'POST'], credentials: true })); app.get('/api/data', (req, res) => { res.json({ message: 'Hello World' }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` 2. **使用代理**: 在开发环境中,可以通过配置代理来绕过CORS限制。例如,在`vue-cli`中,可以在`vue.config.js`中配置代理: ```javascript module.exports = { devServer: { proxy: { '/api': { target: 'http://your-backend-domain.com', changeOrigin: true, pathRewrite: { '^/api': '' } } } } }; ``` 3. **JSONP**: 对于GET请求,可以使用JSONP的方式进行请求,但这需要服务器端的支持,并且只能用于GET请求。 4. **浏览器插件**: 在开发阶段,可以使用浏览器插件如`CORS Unblock`来临时解决CORS问题,但不建议在生产环境中使用。 5. **Nginx反向代理**: 配置Nginx作为反向代理,将前端请求转发到后端服务器,从而绕过CORS限制。 ```nginx server { listen 80; server_name your-frontend-domain.com; location /api/ { proxy_pass http://your-backend-domain.com; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location / { root /path/to/your/frontend/files; try_files $uri $uri/ /index.html; } } ``` 通过以上方法,可以有效地解决前端使用axios发送请求时出现的CORS错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值