Vue测试后端API接口简易模板

Vue测试后端API接口简易模板

大多数vue项目都把页面放在src/views/目录下,并且有src/router/index.js做路由。本项目是vue2版本,主要用于后端开发过程中测试api,只用到api模块。项目结构如图:

src/main.js

1
2
3
4
5
6
7
8
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
render: h => h(App),
}).$mount('#app')

src/App.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
name: 'App',
components: {
HelloWorld
}
}
</script>

<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

src/api/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import Vue from 'vue'
import Axios from 'axios'

const axiosInstance = Axios.create({
withCredentials: true
})

// 通过拦截器处理csrf问题,这里的正则和匹配下标可能需要根据实际情况小改动
axiosInstance.interceptors.request.use((config) => {
config.headers['X-Requested-With'] = 'XMLHttpRequest'
const regex = /.*csrftoken=([^;.]*).*$/
config.headers['X-CSRFToken'] = document.cookie.match(regex) === null ? null : document.cookie.match(regex)[1]
return config
})

axiosInstance.interceptors.response.use(
response => {
return response
},
error => {
return Promise.reject(error)
}
)

Vue.prototype.axios = axiosInstance

export default axiosInstance

src/api/api.js

1
2
3
4
5
6
7
8
9
10
import axiosInstance from './index'

const axios = axiosInstance
const ip = 'http://localhost:8000/app/' // api请求地址的统一字段

// GET请求
export const getRequest = () => {return axios.get(ip + '后端url')}

// POST请求
export const postRequest = data => {return axios.get(ip + '后端url', data)}

src/components/HelloWorld.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>

<script>
import {
getRequest, postRequest
} from '../api/api.js'
export default {
name: 'HelloWorld',
data() {
return {
msg: 'Welcome to Your Vue.js App',
}
},
methods: {
testGetRequest() {
getRequest().then(response => {
console.log(response.data)
}).catch((error) => {
alert(error.response.data)
})
},
testPostRequest() {
postRequest({
// 以字典形式构造POST请求的参数
'key': value,
'key': 'value',
}).then(response => {
console.log(response.data)
}).catch((error) => {
alert(error.response.data)
})
},
},
created: function () {
this.testGetRequest()
this.testPostRequest()
},
}
</script>

Vue测试后端API接口简易模板
https://wangaaayu.github.io/blog/posts/2628a59d/
作者
WangAaayu
发布于
2023年5月25日
更新于
2023年6月6日
许可协议