1.创建目录
2.安装需要用到的axios,mysql, express, body-parser
npm install axios mysql express body-parser --save(回车)
3.server/app.js
// 创建express服务器const express = require('express')const app = express()// 注册解析 表单数据的 body-parserconst bodyParser = require('body-parser')// 将请求响应设置content-type设置为application/jsonconst router = require('./router.js')app.use('/api/*', function(req, res, next) {// 设置请求头为允许跨域res.header("Access-Control-Allow-Origin", "*");// 设置服务器支持的所有头信息字段res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");// 设置服务器支持的所有跨域请求的方法res.header("Access-Control-Allow-Methods", "POST,GET");// next()方法表示进入下一个路由next();});// postapp.use(bodyParser.urlencoded({extended: false }))// 处理json格式的参数app.use(bodyParser.json())// 配置路由app.use(router)// 服务器已经启动app.listen('4000', function(res) {console.log('running...')console.log(res)})
4.server/db.js
在mysql数据库中创建一个test_database数据库,
let mysql = require('mysql')exports.base = (sql, data, callback) => {let connection = mysql.createConnection({host: 'localhost', //本机连接不用改动user: 'root', //root用户一般默认都有,可以不改password: '123456', //改成自己的密码database: 'test_database' //改成自己的数据库名(注意数据库名和表名的区别)})connection.connect();//如果不存在,创建数据库test_database,数据库表Loginconnection.query("create table if not exists Login\(`username` varchar(16) unique not null,`password` varchar(16) not null);", (error, results, fields) => {if (error) throw error; {console.log(error)}console.log(results)})connection.query(sql, data, (error, results, fields) => {if (error) {console.log(error)}console.log(results)callback && callback(results, error)})connection.end();}
5.server/router.js
const express = require('express')const router = express.Router()const services = require('./services.js')// router.get('/',services.start)// 登录功能router.post('/api/login', services.login)// 注册功能router.post('/api/register', services.register)module.exports = router
6.server/services.js
const db = require('./db.js')exports.start = (req, res) => {}// 登录注册处理exports.login = (req, res) => {let username = req.body.usernamelet pwd = req.body.password// 查询语句let sql = 'select * from Login where username = ?'db.base(sql, username, (result, error) => {if (!result.length) {return res.json({status: 0, msg: '登录失败' })} else {// [ RowDataPacket { password: '123', username: 'admin', id: 1 } ]if (result[0].password == pwd) {return res.json({status: 1, msg: '登录成功' })}return res.json({status: 1, msg: '密码错误' })}})}exports.register = (req, res) => {let username = req.body.usernamelet pwd = req.body.password// 插入语句let sql = 'insert into Login values(?,?)'try {db.base(sql, [username, pwd], (result, error) => {if (error) {console.log(result)console.log(error + "12345323")return res.json({status: 0, msg: error.sqlMessage })} else {return res.json({status: 1, msg: "注册成功" })}})} catch (err) {console.log(err)}}
7.src/components/HelloWorld.vue
<template><form><label for="username">用户名:</label><input type="text" v-model="username" id="username"><br><label for="pwd">密码:</label><input type="text" v-model="pwd" id="pwd"><br><button @click.prevent="login">登录</button><button @click.prevent="register">注册</button><div>{{msg}}</div></form></template><script>export default {data(){return {username:'',pwd:'',msg:''//接收数据}},methods:{login(){this.$axios.post(this.HOST+'/api/login',{username:this.username,password:this.pwd}).then(result=>{console.log(result.data)this.msg = result.data.msg}).catch(err=>{console.log(err)})},register(){this.$axios.post(this.HOST+'/api/register',{username:this.username,password:this.pwd}).then(result=>{console.log(result.data)this.msg = result.data.msg}).catch(err=>{console.log(err)})}}}</script>
8.main.js
// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from 'vue'import App from './App'import router from './router'import VueResource from 'vue-resource'import axios from 'axios'Vue.prototype.HOST = 'http://localhost:4000'Vue.config.productionTip = falseVue.prototype.$axios = axios;/* eslint-disable no-new */new Vue({el: '#app',router,components: {App },template: '<App/>'})
9.打开命令行窗口,运行如下命令,注意不同命令运行的路径,
注意:每次对server文件夹中的内容改动,都要重新执行下面的代码
node app.js
npm run dev
10.最后效果展示
挺简陋的,花了一天总算前后端打通了,想要源码的加微信发给你,另附微信:Y17744650906 无偿
觉着不错,有帮助的,点个赞再走,有什么问题欢迎指正
另外需要尚硅谷 八斗学院 奈学教育完整大数据资料和多家机构面试题的加 资料来之不易,不能接受小额有偿的勿扰,谢谢