vue 打包后 设置请求头
时间: 2023-09-03 18:10:05 浏览: 63
在 Vue 打包后,我们需要将 Axios 的请求头设置在 `axios.defaults.headers` 中。
首先,在 `main.js` 中引入 Axios 并设置默认请求头:
```javascript
import axios from 'axios'
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token')
Vue.prototype.$http = axios
```
在上面的代码中,我们设置了一个默认请求头,这样在每个请求中都会自动带上该请求头。
然后,在组件中发送请求时,只需要使用 `this.$http` 即可:
```javascript
this.$http.get('/api/user')
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
```
在这个例子中,我们使用了 `this.$http` 发送了一个 GET 请求,Axios 会自动带上默认请求头。如果需要在某个请求中覆盖默认请求头,可以在请求中设置该请求头即可。例如:
```javascript
this.$http.post('/api/user', data, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
```
在这个例子中,我们在 POST 请求中覆盖了默认请求头,设置了一个名为 Content-Type 的请求头,值为 application/json。