vue通过express创建server连接mysql

vant文档
地址:https://youzan.github.io/vant/#/zh-CN/

安装node
node官网地址:https://nodejs.org/en/

查看是否安装成功

node -v
npm -v
cnpm -v

安装cnpm
使用npm安装依赖模块可能会很慢,建议换成[cnpm]

<!---g表示全局安装 -->
npm install -g cnpm --registry=http://registry.npm.taobao.org

安装vue-cli脚手架工具

cnpm install -g @vue/cli              // 安装 Vue Cli 
cnpm install -g @vue/cli-init         //安装完后 就还可以使用 vue init 命令
npm install axios -save-dev           // 处理http应用请求的包

创建一个项目文件

<!--my-project是项目名-->
vue init webpack my-project 

进入项目内,安装vue-resource依赖

cd my-project
npm install express mysql body-parser
npm i vant -S
npm i babel-plugin-import -D

添加 server 服务端目录
在项目根文件夹下创建一个 server 文件夹。然后里面创建下面一个文件 index.js

index.js——Express 服务器入口文件

// node 后端服务器

var express = require('express');   //引入express模块
var mysql = require('mysql');     //引入mysql模块
var app = express();        //创建express的实例

var connection = mysql.createConnection({      //创建mysql实例
  host: 'localhost',
  user: 'root',                   // mysql用户名
  password: '1234',               // 密码
  database: 'movie',              // 数据库名  注意:需提前建立好数据库,步骤在文末
  port: '3306'                    // 建议使用默认端口3306
});

connection.connect();
var sql = 'SELECT * FROM movie_list';
var str = " ";
connection.query(sql, function (err,result) {
    if(err){
      console.log('[SELECT ERROR]:',err.message);
    }
    str = JSON.stringify(result);
    //数据库查询的数据保存在result中,但浏览器并不能直接读取result中的结果,因此需要用JSON进行解析
    //console.log(result);   //数据库查询结果返回到result中
    // console.log(str);
});

// 增加用户接口
app.get('/list',function (req,res) {
    res.send(str);
});


// connection.end();
app.listen(3000,function () {    监听3000端口
    console.log('Server running at 3000 port');
});

在my-projext/main.js中引入自适应函数
将文件 rem.js reset.css 复制到my-project/src/assets目录下

// 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 './assets/rem'
import './assets/reset.css'
import Vue from 'vue'
import App from './App'
import router from './router'
import VueRouter from 'vue-router'

import { Button } from 'vant'
Vue.use(Button)

import axios from 'axios'
Vue.prototype.axios = axios;

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
});

// 此处需要use后,this.$http.get或者this.$http.post才可以
Vue.use(VueRouter);

设置代理解决跨域
vue-cli 的 config 目录的index.js文件中有一个proxyTable参数,用来设置地址映射表,可以添加到开发时配置(dev)中

dev: {
    env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {        
        '/api': {
            target: 'http://localhost:3000/api/',
            changeOrigin: true,
            pathRewrite: {                
                '^/api': ''
            }
        }
    },
    cssSourceMap: false
  }
}

修改my-project/index.js文件
替换

<meta name="viewport" content="width=device-width,initial-scale=1.0">

为下面文件

<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0">

修改my-project/.babelrc文件

"plugins": [
    "transform-vue-jsx",
    "transform-runtime",
  ["import", {
      "libraryName": "vant",
      "libraryDirectory": "es",
      "style": true
    }]]
}

项目配置完毕
此时在 server 文件夹下执行node index 看到 success listen at port:3000……即服务端启动成功。
在项目my-project目录下运行 npm run dev,看到Your application is running here: http://localhost:8080 ,可以进入浏览器输入http://localhost:8080查看页面

编写前端 vue
HelloWorld.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: '',
    }
  },
  created () {
    axios.get('api/list')
      .then(response => {
      this.msg = response.data;
      console.log(this.msg)
      }
}
</script>

刷新浏览器,可以往数据库添加数据

注意:提前建立好数据库
在cmd运行代码

mysql -u root -p                     // 按提示输入数据库登录密码
create database movie;               // 删除数据库用drop database movie;
show databases;
use movie
show tables;
// 新建表
CREATE TABLE user;(                         
    movie_id CHAR(20) DEFAULT '0000',
    movie_url CHAR(20) DEFAULT '');
// 删除表用 truncate table 表名     drop table 表名;
// 如果pycharm测试连接报错   则登录mysql后输入 set global time_zone='+8:00';
INSERT INTO user (movie_id, movie_url) VALUES ('12345', '34567');           // 往表中插入数据

上传代码到gitee
先在gitee创建仓库,复制下载地址,在上传文件里右键Git Bash Here

第一次上传
git init                                        // 进行git文件夹的创建
git remote add origin https://gitee.com/koiyun/my-project.git    // 添加远程仓库到本地
git pull                                        // 把远程仓库多出的文件拉到本地
git add .                                       //当前文件夹下的所有内容添加到暂存区
git commit -m "initialized"                     // 提交一个版本 备注信息要尽量详细
git push -u origin master -f                    // 将本地仓库中添加的内容上传到远程仓库 强制提交

以后上传
git branch                            // 查看本地分支
git branch [分支名]                    //  创建本地分支
git checkout [分支名]                  // 切换分支
git status                            // 查看分支
git pull                              // 把远程仓库多出的文件拉到本地
提交到gitee
git add .
git commit -m '用express创建服务'
git push -u origin [分支名]
合并分支
git checkout master       //切换到主分支
git merge origin/express  //合并分支
git push                  //推送
下载指定分支到本地
git clone -b [分支名] https://gitee.com/koiyun/my-project.git
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值