Foreword: It is very important to adjust the interface on the road of exploring vue3.0, so I will show the road I have explored to provide convenience for everyone, hope you like it, and show it without talking nonsense! ! !
Step 1: Create an http folder under src, and create a config js file!
The function is: throw the basic request method, basic prefix, request header information, parameters, timeout, credentials, and backend interface return data type!
//import { baseUrl } from '@/utils/global'
export default {
method: 'get',
// 基础url前缀
baseUrl: process.env.BASE_URL,
// 请求头信息
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
// 参数
data: {},
// 设置超时时间
timeout: 10000,
// 携带凭证
withCredentials: true,
// 返回数据类型
responseType: 'json'
}
Step 2: Create an http folder under src, and create an axios js file!
The role is: use request interceptors and response interceptors to solve the following problems
- Create XMLHttpRequests from the browser
- Create http request from node.js
- Support Promise API
- Intercept requests and responses
- Transform request data and response data
- cancel request
- Automatically convert JSON data
- Client supports defense against XSRF
import axios from 'axios'
const request = axios.create({
baseURL: '/api', // 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
timeout: 5000
})
// request 请求器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
if(config && config.headers){
config.headers['Content-Type'] = 'application/json;charset=utf-8';
}
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request
Step 3: Create an http folder under src, for example: create an index.js under a data folder!
The function is: here is the interface url you want to request, the request method post/get, the parameter data, and finally throw it on the page through the export default method!
import axios from "../axios";
export const alldata=(data)=>{
return axios({
url:'/article/data',
method:'post',
data
})
}
export default {alldata}
Step 4: Enter the command in the terminal!
The role is: download axios!
npm i axios -g
Step 5: Mount axios in the main.js root file!
The effect is: vue3 does not support binding global variables in the way of Vue.prototype, and can only be bound globally with app.config.globalProperties.$http !
Image example:
import axios from 'axios'
app.config.globalProperties.$http=axios;
Step 6: Change the configuration in vue.config.js to achieve cross-domain!
The function is: to make an indirect connection with another network terminal (usually a server) through this service, and change the axios
root path of the configuration request in the sending request through the proxy!
// 配置跨域
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
// lintOnSave:false,
devServer: {
port: 8080, // 端口
proxy: {
'/api': { // 若请求的前缀不是这个'/api',那请求就不会走代理服务器
target: 'http://156.61.146.85:8078', //这里写路径
pathRewrite: { '^/api': '' }, //将所有含/api路径的,去掉/api转发给服务器
ws: true, //用于支持websocket
changeOrigin: true //用于控制请求头中的host值
},
}
}
})
Step 7: Write the method to be used, life cycle, initial value, and imported method on the page where the interface needs to be adjusted!
The function is: adjust the interface to render the page!
Image example:
import { reactive,onMounted} from "vue";
import {alldata} from "@/http/Home/home.js"
export default {
name: "app",
setup(){
const datas = reactive({
value:[],
})
const methods = {
requestall(){
const data={
pageNum:10,
pageSize:5,
articieId:100,
};
alldata(data).then(res => {
datas.value=res
console.log(res);
}).catch(err => {
console.log(err)
})
}
}
onMounted(()=>{
methods.requestall()
})
return{
...methods
}
}
}
Result: The interface transferred the 200 status code, the parameter passed the data, and the interface data was also requested, and the interaction before and after vue3.0 was completed! ! !
Image example: