vue.config.js文件配置
const { defineConfig } = require('@vue/cli-service');
module.exports = defineConfig({
lintOnSave: false,
transpileDependencies: true,
devServer: {
port: 8081, //前端运行端口
open: false,
https: false,
proxy: {
"/testConn": {
target: "http://127.0.0.1:4523/m1/1732232-0-default",
changeOrigin: true,
pathRewrite: {
"^/testConn": ""
}
}
}
}
});
在这个 devServer 的配置中,proxy 是用于将前端请求代理到后端的地址的。/testConn 是一个虚拟路径,用于匹配前端发起的请求。当前端发起的请求以 /testConn 开头时,会被代理到指定的 target 地址。(但是很奇怪,用这种方法改login.vue的url时出现了axios报错,直接黏贴apifox中的地址又可以跑通)
router.js文件配置
import { createRouter, createWebHashHistory} from "vue-router";
import log_in from "@/components/log_in.vue";
const routes = [
{
path: '/',
component: log_in
}
]
const router = createRouter ({
history:createWebHashHistory(),
routes
})
export default router;
配置默认路由login,界面一打开显示login组件对应的界面
main.js文件配置
import { createApp } from "vue";
import router from "@/util/router.js";
import ElementPlus from 'element-plus';
import 'element-plus/theme-chalk/index.css';
import locale from 'element-plus/es/locale/lang/zh-cn';
import axios from './axios/http';
import VueAxios from "vue-axios";
import App from "@/App.vue";
const app = createApp(App);
// 将 Axios 实例添加到 Vue 应用的全局属性中
app.config.globalProperties.$http = axios;
// 使用插件和路由
app.use(router)
.use(ElementPlus, { locale })
.use(VueAxios, axios)
.mount('#app');
login.vue文件配置
<template>
<div class="login-wrapper">
<el-form :model="loginForm" class="login-box">
<h3 class="login-title">请登录</h3>
<el-form-item label="名字" prop="name" class="name">
<el-input type="text" v-model="loginForm.username"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password" class="name">
<el-input type="password" v-model="loginForm.password"></el-input>
</el-form-item>
<el-form-item class="login-btn">
<el-button type="primary" @click="gotoMain">登录</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import qs from 'qs';
import http from "@/axios/http";
export default {
name: "log_in",
data() {
return {
loginForm: {
username: '',
password: ''
}
};
},
methods: {
async gotoMain() {
try {
const dd = {
name: this.loginForm.username,
password: this.loginForm.password
};
const response = await http.post('http://127.0.0.1:4523/m1/4196477-0-default/user/login', qs.stringify(dd));
const a = response.data;
if (a) {
alert("登录成功!");
// 在这里可以进行页面跳转等操作
this.$router.push({
name:'main_page'
});
} else {
alert("登录失败!");
}
} catch (error) {
console.error('登录请求失败:', error);
// 在这里可以进行错误处理,例如提示用户登录失败等
}
}
}
};
</script>
<style>
.login-wrapper {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100vh; /* 占满整个屏幕高度 */
}
.login-box {
width: 300px; /* 设置登录框宽度 */
}
.login-title {
margin-bottom: 20px; /* 标题与表单之间的间距 */
}
.login-btn {
text-align: center; /* 按钮居中对齐 */
}
</style>
apifox配置

运行截图

文章详细描述了Vue项目中如何配置devServer的代理、使用axios进行前后端通信以及router.js的路由设置。作者遇到的问题是在login.vue中通过proxy代理登录请求时出现问题,但直接使用API福克斯则可正常运行。

1794

被折叠的 条评论
为什么被折叠?



