vue-cli3连接后台配置文件如何配置
时间: 2024-05-09 13:19:05 浏览: 82
1. 在 `vue.config.js` 文件中配置代理,可以使用 `devServer` 属性来配置代理。
```javascript
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000', // 后台接口地址
changeOrigin: true, // 是否跨域
pathRewrite: {
'^/api': '' // 路径重写
}
}
}
}
}
```
2. 在组件中调用后台接口时,使用相对路径来调用接口,如 `/api/user`,这样就会被代理到后台接口地址。
```javascript
import axios from 'axios'
axios.get('/api/user')
.then(res => {
console.log(res.data)
})
.catch(err => {
console.error(err)
})
```
3. 如果后台接口需要验证身份,可以在请求头中添加 token 等信息。
```javascript
import axios from 'axios'
axios.get('/api/user', {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(res => {
console.log(res.data)
})
.catch(err => {
console.error(err)
})
```
阅读全文
相关推荐

















