vue 如何在ajaxpost请求中使用vue.config的配置地址
时间: 2023-11-27 09:49:02 浏览: 44
可以通过在ajax post请求中使用`axios`库,并在请求拦截器中设置`baseURL`来实现在ajax post请求中使用vue.config的配置地址。
首先,需要在main.js中引入`axios`库,并将其挂载到Vue实例上。例如:
```javascript
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios
```
然后,在`axios`的请求拦截器中,设置`baseURL`为vue.config中的配置地址。例如:
```javascript
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios
axios.interceptors.request.use(function (config) {
config.baseURL = process.env.VUE_APP_BASE_API // vue.config中的配置地址
return config;
}, function (error) {
return Promise.reject(error);
});
```
这样,在ajax post请求中使用`axios`库时,会自动使用vue.config中的配置地址作为请求地址。例如:
```javascript
this.$http.post('/api/login', {
username: this.username,
password: this.password
}).then(response => {
console.log(response.data)
}).catch(error => {
console.log(error)
})
```