📖Vue+node.js 简单获取Mysql 数据库的数据
前言
我的数据库是利用php study在本地搭建的
本地环境已经安装node.js 与 nodejs 中的mysql,http 扩展
Vue代码
<template>
<div id="Nodejs">
<ul>
<li v-for='nodetxt in textAry'>{{nodetxt.name}}</li>
</ul>
<button @click='sqlUP'>获取数据库信息</button>
</div>
</template>
<script>
const axios = require('axios');
export default{
name:"Nodejs",
data(){
return {
NodeApi:'/user',
textAry:[]
};
},methods:{
sqlUP:function(){
this.$axios.get('/Node'+this.NodeApi)
.then(res => (
this.textAry = res.data.data
))
.catch(function(error){console.log('获取失败');});
}
}
}
</script>
<style scoped>
.table th{text-align: center;}
</style>
Node.js 代码
const express = require('express')
const mysql = require('mysql')
const cors = require('cors') // 跨域
const bodyParser = require('body-parser') // 解析参数
const app = express()
const router = express.Router()
//上面是引入各种模块
app.all('*', 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');//允许的header类型
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); //跨域允许的请求方式
if (req.method == 'OPTIONS') {
res.send(200);//让options尝试请求快速结束
} else {
next();
}
});
let ApiProt = 9999;
//启动项目,端口号为8000
app.listen(ApiProt,()=>console.log('服务启动,请访问 http://localhost:'+ApiProt+'/user'))
//数据库信息,密码一般,默认root,我是修改过
const option = {
host:'localhost',
user:'Nodesql',
password:'Nodesql',
port:'3306',
database:'Nodesql',
connectTimeout:5000, // 连接超时
multipleStatements:false // 是否允许一个query中包含多条sql语句
}
app.use(cors()) //解决跨域
app.use(bodyParser.json()) //json请求
app.use(bodyParser.urlencoded({extended:false})) // 表单请求
//连接数据库
const conn = mysql.createConnection(option)
//all代表所有的请求方式(包括get/post) '/user' 给一个路径(自己定义) req代表发起请求(request) res代表接收请求(response)
app.all('/user',(req,res)=>{
// 选择user表 根据你自己的表名 用json的格式输出
conn.query('SELECT * From websites',(e,r)=>res.json(new Result({data:r})))
})
app.all('/user_install',(req,res)=>{
// 选择user表 根据你自己的表名 用json的格式输出
conn.query('SELECT * From websites',(e,r)=>res.json(new Result({data:r})))
})
// 输出的内容
function Result({code=1,msg='',data={}}){
this.code = code;
this.msg = msg;
this.data = data
}
跨域
由于不在同一接口所以会遇到跨域问题,我这里的解决方法是使用代理服务器,也就是我之前文章有写的
http-proxy-middleware 本地代理配置
//config/index.js
proxyTable: {
'/Node':{//Node.js测试
target:"http://localhost:9999",
changeOrigin:true,
pathRewrite:{
'^/Node':'/'
}
}
},





🧐发表评论