Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[vue] axios是什么?怎样使用它?怎么解决跨域的问题? #301

Open
haizhilin2013 opened this issue Jun 20, 2019 · 5 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

[vue] axios是什么?怎样使用它?怎么解决跨域的问题?

@haizhilin2013 haizhilin2013 added the vue vue label Jun 20, 2019
@y841781583
Copy link

axios 的是一种异步请求,用法和ajax类似,安装npm install axios --save 即可使用,请求中包括get,post,put, patch ,delete等五种请求方式,解决跨域可以在请求头中添加Access-Control-Allow-Origin,也可以在index.js文件中更改proxyTable配置等解决跨域问题

@CorgiTT
Copy link

CorgiTT commented Nov 22, 2019

因为axios在vue中利用中间件http-proxy-middleware做了一个本地的代理服务A,相当于你的浏览器通过本地的代理服务A请求了服务端B,浏览器通过服务A并没有跨域,因此就绕过了浏览器的同源策略,解决了跨域的问题。

@qq-radio
Copy link

qq-radio commented Jan 3, 2021

axios跨域:定义baseURL、配置proxyTable

@crush2020
Copy link

axios是一种异步请求方式,有cdn引入和npm方法引入并使用
解决跨域常用的有两种方式
1.CORS解决跨域问题,这需要通过后端来解决,通过设置header头来通配。使服务器允许跨域请求接口数据,而前端正常使用axios请求方式。
2.通过接口代理的方式,在vue项目中创建一个vue.config.js,导入一个devserve,并配置里面的选项即可。

@Cai-zhiji
Copy link

Axios

Axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js环境中发送HTTP请求。它提供了一种简洁、灵活和功能丰富的方式来与后端服务器进行数据交互。

使用方法

要使用Axios,需要先在项目中安装Axios依赖:

npm install axios

然后,在需要发送HTTP请求的地方引入Axios,并使用Axios的方法发送请求,如axios.get、axios.post等。

import axios from 'axios';

// 发送GET请求
axios.get('/api/user')
  .then(response => {
    // 请求成功时的处理
    console.log(response.data);
  })
  .catch(error => {
    // 请求失败时的处理
    console.error(error);
  });

// 发送POST请求
axios.post('/api/user', { name: 'John', age: 25 })
  .then(response => {
    // 请求成功时的处理
    console.log(response.data);
  })
  .catch(error => {
    // 请求失败时的处理
    console.error(error);
  });

Axios提供了丰富的配置选项,可以设置请求头、请求参数、拦截器等。可以参考Axios的官方文档来了解更多使用细节:Axios Github

解决跨域问题

代理服务器:
在开发环境中,可以配置一个代理服务器,将请求转发到目标服务器。
通过配置代理,使得请求在同源策略下成立,解决跨域问题。

CORS(跨域资源共享):
在目标服务器上配置CORS头,允许特定的域或所有域访问服务器的资源。
通过设置合适的响应头,允许跨域请求,解决跨域问题。

JSONP(JSON with Padding):

JSONP是一种利用<script>标签可以跨域加载资源的原理来实现跨域请求的方法。
通过在请求中指定回调函数名,服务器返回一个包含回调函数调用的脚本,从而获取数据。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

6 participants