介绍
Express 框架是一个基于node.js的web应用框架,能够帮你创建一个从前端到后端功能完整的网站;Vue是一个流行的前端框架,主要是用来构建用户界面的,并且具有组件化,响应式等特点;所以理解为 express负责后端,vue负责前端,它俩之间使用HTTP来进行数据交换。
数据库准备
数据库名为 vuelearning,表名为user,详细如下:
开始搭建
1.新建一个vue项目工程
vue create express_learning
2.搭建express环境
安装 express框架
npm install -g express
安装 express-generator
npm install -g express-generator
使用 express --version 来检测是否安装成功
3.新建vue工程项目
vue create express_learning
4.安装相关依赖
npm install express
npm install mysql
npm install body-parser
npm install --save axios
5.调整目录结构
5.1 在项目根目录文件下创建server文件夹,在文件夹中有两个文件(db.js和index.js)和一个api文件夹(含有userApi.js)
示意图如下
内容如下:
db.js,用于数据库连接配置
module.exports = {
mysql: {
host: 'localhost',
user: 'root',//数据库用户名
password: '123456',//数据库密码
database: 'vuelearning',//所用数据库
port: '3306'
}
};
index.js,用于配置后端服务器
//用于配置node后端服务器
// node 后端服务器
const userApi = require('./api/userApi');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// 后端api路由
app.use('/api/user', userApi);
// 监听端口
app.listen(3000);
console.log('success listen at port:3000......');
api/userApi.js,用于数据库增删改查操作
var models = require('../db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
// 连接数据库
var conn = mysql.createConnection(models.mysql);
conn.connect(function (err) {
if (err) {
console.log('[query] - :' + err);
return;
}
else{
console.log('[connection connect] succeed!');
}
});
var jsonWrite = function(res, ret) {
if(typeof ret === 'undefined') {
res.json({
code: '1',
msg: '操作失败'
});
} else {
res.json(ret);
}
};
// 增加用户接口
router.post('/addUser', (req, res) => {
var params = req.body;
var sql = 'insert into user(username, password) values (?, ?)';
console.log(params);
conn.query(sql, [params.username, params.password], function(err, result) {
if (err) {
console.log(err);
}
if (result) {
jsonWrite(res, result);
}
})
});
module.exports = router;
5.2 设置项目主页
在根目录下的views文件夹下新建Hello.Vue
代码如下:
<template>
<div>
{{msg}}
<div>
<input type="text" v-model="username">
<input type="password" v-model="password">
<button @click="addUser">新增</button>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'hello',
data () {
return {
msg: 'Welcome to Your Vue.js App',
username: '',
password: '',
// tableData: [],
}
},
methods: {
// 新增函数
addUser() {
var username = this.username;
var password = this.password;
axios({
method:"post",
url:"http://localhost:3000/api/user/addUser",
data:{
username:username,
password:password
}
}).then(({data})=>{
console.log(data)
})
},
}
}
</script>
<style scoped>
</style>
6.解决跨域问题
6.1 启动项目
启动后端
cd server
node index.js
启动前端
npm run serve
6.2 输入内容点击“新增”,会报错
6.3 在根目录下的vue.config.js下添加以下内容
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',//目标地址
ws: true, //是否启用websockets
changeOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite: {'^/api': '/'} //这里重写路径
}
}
}
6.4 修改hello.vue中的axios请求url内容
url:"/api/api/user/addUser"
6.5 项目重启
6.6 成功运行
7.实现用户登录并查看个人信息
7.1 安装vant框架和vue-cookies
vant框架为移动端框架
npm i vant
npm i babel-plugin-import -D
vant 框架官方手册
https://vant-contrib.gitee.io/vant/#/zh-CN/quickstart
7.2 配置vant
在.babelrc 或 babel.config.js 中添加配置:
{
"plugins": [
[
"import",
{
"libraryName": "vant",
"libraryDirectory": "es",
"style": true
}
]
]
}
在main.js 中引用相关组件:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import { Button } from 'vant';
import { Form, Field, CellGroup } from 'vant';
import { Toast } from 'vant';
createApp(App)
.use(store)
.use(router)
.use(Button)
.use(Form)
.use(Field)
.use(CellGroup)
.use(Toast)
.mount('#app')
7.3删除APP.vue中的四行代码
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
7.4 在userApi.js下添加接口:根据userid获取信息
// 获取用户详细信息
router.post('/getinfo', (req, res) => {
var params = req.body;
var sql = "select * from user where name ='"+params.username+"'";
console.log(sql);
conn.query(sql, [params.username], function(err, result) {
if (err) {
console.log(err);
}
if (result) {
console.log(res);
jsonWrite(res, result);
}
})
});
7.5 文件结构调整
在views下新建main文件夹,里面放一个index.vue文件
内容如下:
<template>
<div class="title" style="font-size: 30px">我的界面</div>
<div class="sub-title" style="font-size: 15px">
查看当前登录用户的个人详情页面
</div>
<van-cell-group inset>
<van-field
v-model="userid"
name="用户id"
label="用户id"
placeholder="用户id"
/>
<van-field
v-model="username"
name="用户名"
label="用户名"
placeholder="用户名"
/>
<van-field
v-model="userphone"
name="电话"
label="电话"
placeholder="电话"
/>
<van-field
v-model="useraddress"
name="地址"
label="地址"
placeholder="地址"
/>
<van-field v-model="company" name="公司" label="公司" placeholder="公司" />
</van-cell-group>
<div style="margin: 16px">
<van-button color="#1E3A8A" block type="primary" native-type="submit" to="/">
退出登录
</van-button>
</div>
</template>
<script>
import { ref } from "vue";
import axios from "axios";
export default {
name: "MeIndex",
components: {},
props: {},
data() {
const userid = ref("");
const username = ref("");
const userphone = ref("");
const useraddress = ref("");
const company = ref("");
return { userid, username, userphone, useraddress, company };
},
computed: {},
watch: {},
created() {
this.userid = this.$route.params.userid;
axios({
method: "post",
url: "/api/api/user/getinfo",
data: {
username: this.userid,
},
}).then(({ data }) => {
console.log(data);
this.userid = data[0].id;
this.username = data[0].username;
this.userphone = data[0].tel;
this.useraddress = data[0].address;
this.company = data[0].company;
});
},
mounted() {},
methods: {},
};
</script>
<style scoped lang="less"></style>
7.5 修改Hello.vue如下
<template>
<div>
<van-form @submit="onSubmit">
<div class="title" style="font-size: 30px">登陆界面</div>
<div class="sub-title" style="font-size: 15px">
登录账号来使用各种提供的服务
</div>
<van-cell-group inset>
<van-field
v-model="id"
name="账号"
label="账号"
placeholder="账号"
:rules="[{ required: true, message: '请填写账号' }]"
/>
<van-field
v-model="pwd"
type="password"
name="密码"
label="密码"
placeholder="密码"
:rules="[{ required: true, message: '请填写密码' }]"
/>
</van-cell-group>
<div style="margin: 16px">
<van-button
type="primary"
native-type="submit"
size="normal"
@click="login()"
block
color="#1E3A8A"
>
登录
</van-button>
</div>
</van-form>
</div>
</template>
<script>
import { ref } from "vue";
import { Toast } from "vant";
import axios from "axios";
export default {
name: "LoginIndex",
components: {},
props: {},
data() {
const id = ref("");
const pwd = ref("");
const onSubmit = (values) => {
console.log("submit", values);
};
return { id, pwd, onSubmit };
},
computed: {},
watch: {},
created() {},
mounted() {},
methods: {
login() {
console.log("点击了登录按钮");
axios({
method: "post",
url: "/api/api/user/getinfo",
data: {
username:this.id,
},
}).then(({ data }) => {
console.log(data);
if (data[0].password==this.pwd) {
Toast.success("登录成功");
this.$router.push(
{
name:"main",
params:{
userid:this.id
}
}
)
} else {
Toast.fail("登陆失败");
}
});
},
},
};
</script>
<style scoped lang="less">
.title {
font-weight: bold;
}
</style>
7.6 配置路由
配置router下的index.js文件
加入以下内容
{
path:'/main',
name:'main',
component:() => import('@/views/main/index.vue')
},
7.7 运行,成功!
输入正确账号密码
输入错误账号密码