axios 跨域配置
时间: 2023-06-29 13:19:41 浏览: 243
在使用 axios 进行跨域请求时,需要进行一些配置,以下是一个基本的跨域配置示例:
```javascript
import axios from 'axios'
axios.defaults.baseURL = 'http://api.example.com'
axios.defaults.withCredentials = true
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token')
axios.interceptors.response.use(
response => {
return response
},
error => {
if (error.response.status === 401) {
// 处理未授权的情况
console.log('Unauthorized')
}
return Promise.reject(error)
}
)
```
其中,`baseURL` 是你要请求的域名,`withCredentials` 表示是否允许发送跨域 cookie,`headers` 中可以设置公共的请求头,例如上面的示例中设置了一个 Bearer Token。另外,`interceptors` 中可以对响应进行拦截处理,例如处理未授权的情况。
相关问题
axios跨域代理配置
可以尝试在配置文件中添加以下代码:
```javascript
module.exports = {
devServer: {
// ...
proxy: {
'/api': {
target: 'http://api.example.com', // 实际要请求的服务器URL
changeOrigin: true, // 允许跨域
pathRewrite: { // 重写路径
'^/api': ''
}
}
}
}
}
```
这样,在前端请求后端API时,只需要将请求的路径改为`/api`开头即可。比如请求`http://api.example.com/test`,可以写成`/api/test`,axios会将`/api`重写为实际请求的服务器URL,并加上`/test`,从而实现跨域请求。
vue配置axios跨域代理
在 Vue 项目中,可以通过配置 `vue.config.js` 文件来实现跨域代理。具体步骤如下:
1. 在项目根目录下创建 `vue.config.js` 文件(如果已存在则直接打开该文件)。
2. 在该文件中添加以下代码:
```javascript
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000', // 修改为你的目标后端服务地址
changeOrigin: true, // 允许跨域
pathRewrite: {
'^/api': '' // 将 /api 前缀替换为空字符串
}
}
}
}
}
```
以上代码中,我们将 `/api` 前缀的请求转发到了 `http://localhost:3000` 地址,你可以根据实际情况进行修改。
3. 在前端代码中使用 axios 发送请求时,将请求地址的前缀修改为 `/api`,如下所示:
```javascript
axios.get('/api/users').then(response => {
console.log(response.data)
})
```
这样就完成了跨域代理的配置。
阅读全文
相关推荐
















