vue3跨域配置axios
时间: 2023-11-22 07:47:33 浏览: 86
3跨域配置axios需要在项目中安装axios和cors插件。在main.js中,需要通过Vue构造函数的prototype原型对象全局配置axios,并在axios的请求拦截器中设置跨域请求的相关配置。具体步骤如下:
1. 安装axios和cors插件
```
npm install axios cors --save
```
2. 在main.js中导入axios和cors插件,并配置axios的请求根路径
```javascript
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
import cors from 'cors'
axios.defaults.baseURL = 'https://www.example.com'
const app = createApp(App)
app.use(cors())
app.config.globalProperties.$http = axios
app.mount('#app')
```
3. 在axios的请求拦截器中设置跨域请求的相关配置
```javascript
axios.interceptors.request.use(config => {
config.headers['Access-Control-Allow-Origin'] = '*'
config.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
config.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
return config
})
```
阅读全文