首先使用axios发送请求到模拟服务器上,再将mock.js模拟服务器数据返回给客户端。打包工具使用的是vite。
1.安装
npm i axios -S
npm i mockjs --save-dev
npm i vite-plugin-mock --save-dev
2.在vite.config.js文件中配置vite-plugin-mock等消息
import { viteMockServe } from 'vite-plugin-mock'
plugins: [vue(),
viteMockServe({
supportTs:true,
logger: false,
mockPath: "./mock/" // 注意:此时的 mockPath 地址是真正安装的 mock 文件夹的地址;
})
]
3.在根目录下创建mock文件夹及index.js文件:
4.在index.js文件中进行配置:
import Mock from 'mockjs'
const listUser = function() {
const a = Mock.mock({
'list|1-20':[{
'userId|+1':0,
'userName|1':["张三",'李四',"鲍勃","丽丽","李阳","杨洋","王五","周星星","大仙","孤影"],
'role|1':["系统管理员","操作人员","销售","平台管理者","仓库管理员","部长"],
}]
})
return a;
}
export default [
{
url:'/hello',
method:'get',
response: () => {
return listUser;
}
}
]
5.在页面中需要发送请求获取数据时,使用axios发送请求:
1)在request.js文件中创建axios
import axios from 'axios'
const request = axios.create({
baseURL:"http://127.0.0.1:5173/",
})
export default request
2)在需要发送请求的页面编写一下内容:
import request from './utils/request';
request({
method: 'GET',
url: "/hello",
}).then((res) => {
console.log(res);
})
显示结果:
如果显示报错:Access to XMLHttpRequest at ‘http://localhost:5173’ from origin ‘http://127.0.0.1:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
说明使用mock.js时遇到了跨域,需要进行以下配置:
1.在vite.config.ts中进行数据代理:
export default defineConfig({
plugins: [
vue(),
viteMockServe({
supportTs:true,
logger:false,
mockPath:"./mock/"
})
],
server: {
proxy: {
'/api': {
target:'http://127.0.0.1:5173/',
changeOrigin:true,//支持跨域
rewrite:(path) => path.replace(/^\/api/,""),//重写路径,替换/api
}
}
},
})
2.在axios基地址中添加/api即可
import axios from 'axios'
const request = axios.create({
baseURL:"/api",
timeout:5000
})
export default request