赞
踩
创建相关的库表结构:
引入需要的模块(mysql、http、vue-resource)
// 找到项目所在位置(进行DOS命令)、项目中拥有可以不重复引用
cnpm install mysql --save
cnpm install http --save
cnpm install vue-resource --save
点击package.json,查看是否引入成功:
在项目根目录下创建server文件夹:
编写server.js文件,作为Node服务端:
// 获取http、mysql模块
let http = require('http');
let mysql = require('mysql');
const server = http.createServer(function (req, res) {
res.statusCode = 200;
// 处理跨域问题
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.setHeader("X-Powered-By", ' 3.2.1');
res.setHeader("Content-Type", "application/json;charset=utf-8");
res.setHeader('Content-Type', 'text/plain;charset=utf-8');
});
// 创建一个数据库连接池
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
port: '3306',
password: 'root',
database: 'test'
});
// 开始连接
connection.connect(function (err) {
if (err) {
console.log("数据库连接失败!!!");
} else {
console.log("数据库连接成功!!!");
}
});
server.on('request', function (request, response) {
let url = request.url;
console.log("获取访问映射地址:" + url);
// 参数方式,类似于mybatis
var sql = '';
var sqlParams = [];
// 方法一:查询数据
if (url === '/select') {
sql = 'select * from test.user where username = ?';
sqlParams = ['小辰哥哥'];
connection.query(sql, sqlParams, function (err, row) {
if (err) {
console.log("网络异常:" + err);
} else {
// 响应数据
let data = JSON.stringify(row);
response.end(data);
}
})
}
// 方法二:新增数据
if (url === '/insert') {
sql = 'insert into test.user values(?,?)';
sqlParams = ['周大猪', '123456'];
connection.query(sql, sqlParams, function (err, row) {
if (err) {
console.log("网络异常:" + err);
} else {
// 响应数据
let data = JSON.stringify(row);
response.end(data);
}
})
}
// 方法三:修改数据
if (url === '/update') {
sql = 'update test.user set password = ? where username = ?';
sqlParams = ['123456', '小辰哥哥'];
connection.query(sql, sqlParams, function (err, row) {
if (err) {
console.log("网络异常:" + err);
} else {
// 响应数据
let data = JSON.stringify(row);
response.end(data);
}
})
}
// 方法四:删除数据
if (url === '/delete') {
sql = 'delete from test.user where username = ?';
sqlParams = ['周大猪'];
connection.query(sql, sqlParams, function (err, row) {
if (err) {
console.log("网络异常:" + err);
} else {
// 响应数据
let data = JSON.stringify(row);
response.end(data);
}
})
}
});
// 开始Node服务器端口
server.listen(8088, () => {
console.log("服务器端口开启成功!");
});
在src目录下,main.js中使用vue-resource模块:
// 将vue-resource模块引入进来,否则this.$http将无法使用
import VueResource from 'vue-resource'
Vue.use(VueResource);
编写demo.vue开始进行交互操作:
// 在路由中引入新demo.vue页面
import demo from "@/components/demo";
{
path: '/demo',
name: 'demo',
component: demo,
}
<template>
<div style="margin-left: 100px">
<h3>数据库增删改查(CURD操作)</h3>
<label>用户名:<input type="text" v-model="username"/></label><br/><br/>
<label>密码:<input type="password" v-model="password"/></label><br/><br/>
<el-button type="primary" @click="selectData">查询</el-button>
<el-button type="primary" @click="insertData">增加</el-button>
<el-button type="primary" @click="updateData">修改</el-button>
<el-button type="primary" @click="deleteData">删除</el-button>
</div>
</template>
<script>
export default {
name: "demo",
data() {
return {
username:'',
password:'',
}
},
methods: {
selectData() {
// 访问node.js服务端
this.$http.get('http://localhost:8088/select',{
}).then(data => {
if(data.data[0].username == this.username && data.data[0].password == this.password){
this.$message({type: 'success',message:"查询成功"});
}else{
this.$message({type: 'warning',message:"查询失败"});
}
}).catch(error => {
this.$message({type: 'error',message:"网络连接异常"});
});
},
insertData(){
// 访问node.js服务端
this.$http.get('http://localhost:8088/insert',{
}).then(data => {
if(data.data.affectedRows > 0){
this.$message({type: 'success',message:"新增成功"});
}else{
this.$message({type: 'warning',message:"新增失败"});
}
}).catch(error => {
this.$message({type: 'error',message:"网络连接异常"});
});
},
updateData(){
// 访问node.js服务端
this.$http.get('http://localhost:8088/update',{
}).then(data => {
if(data.data.affectedRows > 0){
this.$message({type: 'success',message:"修改成功"});
}else{
this.$message({type: 'warning',message:"修改失败"});
}
}).catch(error => {
this.$message({type: 'error',message:"网络连接异常"});
});
},
deleteData(){
// 访问node.js服务端
this.$http.get('http://localhost:8088/delete',{
}).then(data => {
if(data.data.affectedRows > 0){
this.$message({type: 'success',message:"删除成功"});
}else{
this.$message({type: 'warning',message:"删除失败"});
}
}).catch(error => {
this.$message({type: 'error',message:"网络连接异常"});
});
}
}
}
</script>
<style scoped>
</style>
在server目录下,开启Node服务:
开始测试:
查询操作:
增加操作:
修改操作:
删除操作:
引入需要的模块(mysql、express、body-parser、cors、vue-resource)
// 找到项目所在位置(进行DOS命令)、项目中拥有可以不重复引用
cnpm install mysql --save
cnpm install express --save
cnpm install body-parser --save
cnpm install cors --save
cnpm install vue-resource --save
在项目根目录下创建server文件夹:
在src目录下,main.js中使用vue-resource模块:
// 将vue-resource模块引入进来,否则this.$http将无法使用
import VueResource from 'vue-resource'
Vue.use(VueResource);
在server目录下,编写database.js:
// 配置数据库相关信息
module.exports = {
mysql: {
host: "localhost",
user: "root",
password: "root",
database: "test",
port: 3306
}
};
在server目录下,编写sql.js:
// 编写相关sql语句
let sqlMap = {
user: {
// 查询数据
select: "select * from user where username = ?;",
// 插入数据
insert: "insert into user values(?,?);",
// 修改数据
update: "update user set password = ? where username = ?;",
// 删除数据
delete: "delete from user where username = ? and password = ?;"
}
};
// 暴露sqlMap
module.exports = sqlMap;
在server目录下,编写api.js:
// 引入database.js文件(配置数据库相关信息)
let models = require('./database');
// 引入sql.js文件(编写相关sql语句)
let $sql = require('./sql');
// 引入mysql和express模块
let mysql = require('mysql');
let express = require('express');
let router = express.Router();
// 开始连接数据库
let conn = mysql.createConnection(models.mysql);
conn.connect();
// 对JSON字符串进行处理
let jsonWrite = function (response, result) {
if (typeof result === 'undefined') {
response.json({
code: '500',
msg: '操作失败'
});
} else {
response.json(result);
}
};
// 查询数据('/select')
router.post('/select', (request, response) => {
// 获取编写相关sql语句
let sql = $sql.user.select;
console.log("相关sql语句:", sql);
// 获取请求参数
let params = request.body;
console.log("相关参数", params);
// [params.username]传参类似mybatis
conn.query(sql, [params.username], function (error, result) {
if (error) {
console.log('网络连接异常:' + error);
}
if (result) {
jsonWrite(response, result);
for (let i = 0; i < result.length; i++) {
if (result[i].password == params.password) {
return response.end();
} else {
return response.end();
}
}
}
})
});
// 插入数据('/insert')
router.post('/insert', (request, response) => {
// 获取编写相关sql语句
let sql = $sql.user.insert;
console.log("相关sql语句:", sql);
// 获取请求参数
let params = request.body;
console.log("相关参数", params);
// [params.username]传参类似mybatis
conn.query(sql, [params.username, params.password], function (error, result) {
if (error) {
console.log('网络连接异常:' + error);
}
if (result) {
jsonWrite(response, result);
}
})
});
// 修改数据('/update')
router.post('/update', (request, response) => {
// 获取编写相关sql语句
let sql = $sql.user.update;
console.log("相关sql语句:", sql);
// 获取请求参数
let params = request.body;
console.log("相关参数", params);
// [params.username]传参类似mybatis
conn.query(sql, [params.password, params.username], function (error, result) {
if (error) {
console.log('网络连接异常:' + error);
}
if (result) {
jsonWrite(response, result);
}
})
});
// 删除数据('/delete')
router.post('/delete', (request, response) => {
// 获取编写相关sql语句
let sql = $sql.user.delete;
console.log("相关sql语句:", sql);
// 获取请求参数
let params = request.body;
console.log("相关参数", params);
// [params.username]传参类似mybatis
conn.query(sql, [params.username, params.password], function (error, result) {
if (error) {
console.log('网络连接异常:' + error);
}
if (result) {
jsonWrite(response, result);
}
})
});
// 暴露router
module.exports = router;
在server目录下,编写server.js:
// 引入api.js
const userApi = require('./api');
// 引入express模块
const express = require('express');
const app = express();
// 引入cors模块,处理跨域问题
const cors = require('cors');
app.use(cors());
// 引入body-parser模块,解析请求过来的参数
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// 访问Node服务端映射地址
app.use('/api', userApi);
// 开始服务器端口
app.listen(8088);
console.log("服务器端口开启成功!");
编写demo2.vue开始进行交互操作:
// 在路由中引入新demo2.vue页面
import demo2 from "@/components/demo2";
{
path: '/demo2',
name: 'demo2',
component: demo2,
}
<template>
<div style="margin-left: 100px">
<h3>数据库增删改查(CURD操作)</h3>
<label>用户名:<input type="text" v-model="username"/></label><br/><br/>
<label>密码:<input type="password" v-model="password"/></label><br/><br/>
<el-button type="primary" @click="selectData">查询</el-button>
<el-button type="primary" @click="insertData">增加</el-button>
<el-button type="primary" @click="updateData">修改</el-button>
<el-button type="primary" @click="deleteData">删除</el-button>
</div>
</template>
<script>
export default {
name: "demo2",
data() {
return {
username: '',
password: '',
}
},
methods: {
selectData() {
// 访问node.js服务端(参数名称:要和api.js中[params.属性名]一致,请求方式也应该保持一致)
this.$http.post('http://localhost:8088/api/select', {
username: this.username
}).then(data => {
if (data.data[0].username == this.username && data.data[0].password == this.password) {
this.$message({type: 'success', message: "查询成功"});
} else {
this.$message({type: 'warning', message: "查询失败"});
}
}).catch(error => {
this.$message({type: 'error', message: "网络连接异常"});
});
},
insertData() {
// 访问node.js服务端(参数名称:要和api.js中[params.属性名]一致,请求方式也应该保持一致)
this.$http.post('http://localhost:8088/api/insert', {
username: this.username,
password: this.password
}).then(data => {
if (data.data.affectedRows > 0) {
this.$message({type: 'success', message: "新增成功"});
} else {
this.$message({type: 'warning', message: "新增失败"});
}
}).catch(error => {
this.$message({type: 'error', message: "网络连接异常"});
});
},
updateData() {
// 访问node.js服务端(参数名称:要和api.js中[params.属性名]一致,请求方式也应该保持一致)
this.$http.post('http://localhost:8088/api/update', {
username: this.username,
password: this.password
}).then(data => {
if (data.data.affectedRows > 0) {
this.$message({type: 'success', message: "修改成功"});
} else {
this.$message({type: 'warning', message: "修改失败"});
}
}).catch(error => {
this.$message({type: 'error', message: "网络连接异常"});
});
},
deleteData() {
// 访问node.js服务端(参数名称:要和api.js中[params.属性名]一致,请求方式也应该保持一致)
this.$http.post('http://localhost:8088/api/delete', {
username: this.username,
password: this.password
}).then(data => {
if (data.data.affectedRows > 0) {
this.$message({type: 'success', message: "删除成功"});
} else {
this.$message({type: 'warning', message: "删除失败"});
}
}).catch(error => {
this.$message({type: 'error', message: "网络连接异常"});
});
}
}
}
</script>
<style scoped>
</style>
在server目录下,开启Node服务:
开始测试:
查询操作:
增加操作:
修改操作:
删除操作:
每天一个提升小技巧!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。