当前位置: 首页 > 后端技术 > Node.js

Node+Express+Vue+Element+MySQL简单实现前后端分离

时间:2023-04-03 18:31:13 Node.js

源码1.安装node环境。具体安装教程请参考http://nodejs.cn/2。塔式搭建的Vue前端项目使用vue-cli脚手架vue-cli命令行工具全局安装vue-cli$npminstall--globalvue-clicreateanewprojectbasedonwebpacktemplate$vueinitwebpackneveminstalldependencies,letyougo$cdnevem$npminstall$npmrundev注意:npminstall--globalvue-cli全局安装vue-cli。vueinitwebpacknevem基于webpack模板创建一个新项目。这一步建议下图中的单元测试和代码检查工具都填no,否则会增加项目的体积,写代码的时候也会因为不规范而产生很多错误。cdnevem安装vue-resource和element-ui依赖:cdnevem进入前端工程后,找到package.json文件对应的地方,确保添加如下代码:"dependencies":{"element-ui":"^1.3.2","vue":"^2.2.6","vue-resource":"^1.0.3","vue-router":"^2.3.1"},npminstall安装所有的依赖,包括上一步的elementUI和vue-resource。执行npminstall安装时间会稍长,所以推荐使用淘宝cnpm镜像(自己google),如果公司网络被屏??蔽请无视。npmrundev后,会自动弹出http://localhost:8080/#/页面,说明基于webpack的Vue项目创建成功。3、引入Element组件并修改src/main.js为如下代码,引入element和resourceimportVuefrom'vue'importAppfrom'./App'importrouterfrom'./router'importVueResourcefrom'vue-resource'importElementUIfrom'element-ui'import'element-ui/lib/theme-default/index.css'Vue.config.productionTip=falseVue.use(VueResource)Vue.use(ElementUI)/*eslint-disableno-new*/newVue({el:'#app',router,template:'',components:{App},render:h=>h(App)})修改src/componentsHello.vue文件到如下代码,调整首页内容保存以上文件后,在nevem目录下再次运行npmrundev,页面变成如下效果,则表示成功引入element组件4.安装Mysql安装mysql的方法有很多种.这里我使用WampServer搭建数据库。如果想安装使用,还是可以自己google一下。这里我新增了一个名为mbvr_live的数据库,然后在数据库中创建了一个表goods并插入了两条记录,具体的sql代码如下:CREATETABLEIFNOTEXISTS`goods`(`id`int(11)NOTNULLAUTO_INCREMENT,`name`varchar(100)NOTNULL,`price`float(10,2)NOTNULL,`creat_time`timestampNOTNULLDEFAULTCURRENT_TIMESTAMPONUPDATECURRENT_TIMESTAMP,主键(`id`),唯一键`))ENGINE=InnoDBDEFAULTCHARSET=latin1AUTO_INCREMENT=6;INSERTINTO`goods`(`id`,`name`,`price`,`creat_time`)VALUES(1,'apple',5.00,'2017-05-1100:22:10'),(2,'banner',5.00,'2017-05-1101:37:37');5、安装Express,在nevem目录下新建一个文件服务,用作服务器。在里面创建如下4个文件,结构如下:db.js,用于配置mysql连接数据:module.exports={mysql:{host:'localhost',user:'root',password:'',database:'mbvr_live'}}app.js,Expressserverentryfile://nodebackendserverentryconstuserApi=require('./api/userApi');constfs=require('fs');constpath=require('path');constbodyParser=require('body-parser');constexpress=require('express');constapp=express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({extended:false}));//注册api路由app.use('/api/user',userApi);//监听端口app.listen(3000);console.log('成功监听端口:3000...');sqlMap.js,api逻辑调用的SQL语句映射文件://sql语句varsqlMap={//useruser:{add:'insertintogoods(id,name,price)values(0,?,?)'}}module.exports=sqlMap;userApi.js,测试示例:varmodels=require('../db/db');varexpress=require('express');varrouter=express.Router();varmysql=require('mysql');var$sql=require('../db/sqlMap');//连接数据库varconn=mysql.creatConnection(models.mysql);conn.connect();varjsonWrite=function(res,ret){if(typeofret==='undefined'){res.json({code:'1',msg:'operation失败'});}else{res.json(ret);}};//添加用户界面router.post('/addUser',(req,res)=>{varsql=$sql.user.add;varparams=req.body;console.log(params);conn.query(sql,[params.name,params.price],function(err,result){if(err){console.log(err);}if(result){jsonWrite(res,result);}})});//添加用户界面router.get('/addUser',(req,res)=>{res.send('retrunJson');});module.exports=router;写入完成后,你可以在服务项目npminstallexpressmysqlbody-parser下安装相关依赖;此时执行service文件夹下的nodeapp,在port:3000上看到successlisten,即服务器启动成功6.此时回到http://localhost:8080/#/页面,进入名称和价格并提交,发现报404错误到http://localhost:8080/api/use...,这是因为后端8080和前端3000是两个不同的端口,交叉领域。这时找到文件configindex.js,开发配置dev中的地址映射表proxyTable内容为空,这里改为:proxyTable:{'/api':{target:'http://127.0.0.1:3000/api/',//不写localhostchangeOrigin:true,//true允许跨域服务器端,可以跳过这一段}}},结束。查看原文:Node+Express+Vue+Element+MySQL简单实现前后端分离