用vue调用http接口
时间: 2023-02-10 07:29:33 浏览: 57
vue.js 可以使用 axios 库来调用 HTTP 接口。
首先,安装 axios:
```
npm install axios
```
然后,在 vue 项目中使用 axios 调用接口:
```
import axios from 'axios'
export default {
name: 'my-component',
methods: {
async getData() {
try {
const response = await axios.get('http://example.com/api/endpoint')
console.log(response.data)
} catch (error) {
console.error(error)
}
}
}
}
```
你也可以使用全局 axios 默认配置来避免每次请求都手动配置相同的选项。例如:
```
import axios from 'axios'
axios.defaults.baseURL = 'http://example.com/api/'
axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN'
export default {
name: 'my-component',
methods: {
async getData() {
try {
const response = await axios.get('/endpoint')
console.log(response.data)
} catch (error) {
console.error(error)
}
}
}
}
```
这样,每个 axios 请求都会使用这些默认配置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)