一、使用npm安装MySQL

二、编写取数api

1、新建数据库连接信息文件

module.exports={
	mysql:{
			host:'127.0.0.1',
			user:'root',
			password:'x5',
			database:'test',
			port:'3306'
	}
}

2、在服务器文件index.js, 创建数据库连接,并编写取数api

// node 后端服务器
const db=require('./db.js');//数据库连接信息

const mysql=require('mysql');
const express = require('express'); 
const app = express();
app.use(express.static('../dist'));    
var server = require('http').createServer(app);

var conn=mysql.createConnection(db.mysql);
conn.connect();

app.get('/list', function (req, res) {
  	conn.query('select FIRST_ from act_id_user', function (error, results, fields) {
	  if (error) throw error;
	  res.end(results);
	});
})

// 监听端口
server.listen(3000);
console.log('success listen at port:3000......');

三、vue页面使用axios调用api,显示数据

1、安装axios,并将axios引入到页面,在main.js中添加到vue全局对象中

import axios from 'axios'

Vue.prototype.$axios=axios

2、在组件中调用接口

var _this=this;
this.$axios.get('/api/list', {})
.then(function (response) {
     _this.users=[];
     response.data.forEach(function(item,index){
           _this.users.push({
                 'name':item.FIRST_
           });
     }); 
}).catch(function (error) {
       console.log(error);
});

3、处理跨域问题:在config/index.js中

 proxyTable: {
            '/api': {
                target:'http://127.0.0.1:3000', // 你请求的第三方接口
                changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
                pathRewrite:{  // 路径重写,
                    '^/api': '/api'  // 替换target中的请求地址,也就是说以后你在请求http://api.jisuapi.com/XXXXX这个地址的时候直接写成/api即可。
                }
            }
    },

4、在页面显示数据,浏览器输入 http://localhost:8080/#/test

<ul>
   <li v-for="user in users">
        {{user.name}}
    </li> 
</ul>

Logo

前往低代码交流专区

更多推荐