Teach you how to use vue + node as the backend to connect to the database

Sequence of tutorials:

1. Write node server

2. Connect to the database with node

3. Write the front-end page

4. Front-end and back-end interaction

ok let's get started

1. Write node server

First download a few dependent packages

express (for network connections) 

npm i express --save

cors (for handling cross domain issues)

npm i cors --save

Next, we still need to process the data sent by the front end. There is no special processing for the get request, but the data type sent for the post request depends on the type of the content-type of the post request header. Common three

multipart/form-data , application/x-www-form-urlencode , application/json (most common)

If you want to know more about these types, you can use Baidu

In order to handle these types, several dependency packages need to be downloaded

npm i body-parser --save
npm i connect-multiparty --save

 Create a new index.js file

/*
 * @Author: maximing
 * @Date: 2022-12-28 09:06:42
 * @LastEditTime: 2022-12-28 11:23:40
 * @LastEditors: your name
 * @Description: 请添加描述
 * @FilePath: \domysql\src\server\index.js
 */

const express = require('express')
const app = express()

const cors = require('cors') //解决跨域问题
app.use(cors())

const bodyParser = require('body-parser')
const multiparty = require('connect-multiparty')
// 处理 x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: true }))
// 处理 mutipart/form-data
app.use(multiparty())
// 处理 application/json
app.use(bodyParser.json())

//一个简单的测试接口
app.get('/test',(req,res)=>{
    res.send('测试用的接口')
})

//监听node服务器的端口号
app.listen(3000, () => {
	console.log('恭喜你,服务器启动成功')
})

 Next start the node server. Enter the folder where the corresponding index.js is located, enter cmd in the search bar and press Enter to enter the terminal

Start the index.js file just written

Then open the browser and enter localhost:3000/  

 The port number 3000 is what we used when listening just now, and it is the port number of our node service

At this point we have completed the server setup and wrote a simple interface!

2. Connect to the database with node

First download a dependent mysql (for connecting to the database)

npm i mysql --save

Create a new mysql.js file, which is at the same level as index.js

/*
 * @Author: maximing
 * @Date: 2022-12-28 09:33:17
 * @LastEditTime: 2022-12-28 09:52:00
 * @LastEditors: your name
 * @Description: 请添加描述
 * @FilePath: \domysql\src\server\mysql.js
 */

const mySql = require('mysql')
//连接数据库的配置信息
const db_config = { 
	host: 'localhost', //本地都是localhost
	user: 'root', //账户名
	password: '12345', //密码
	port: '3306', //端口号
	database: 'demo' //数据库的名称
}

function conMysql(sql) {
    //创建数据库连接池
	let Myconnect = mysql.createConnection(db_config)
	//开始连接数据库
	Myconnect.connect(function (err) {
		if (err) {
			console.log(`myqsl连接失败:${err}!`)
		} else {
			console.log('恭喜哦,mysql连接成功哦')
		}
	})

	//因为query查询是一个异步操作,所以用promise来操作
	return new Promise((resolve, reject) => {
        //query() 函数用于mysql语句查询
		connect.query(sql, (err, result) => {
			if (err) {
				reject(err)
			} else {
				let res = JSON.parse(JSON.stringify(result))
				closeMysql(connect)  //调用函数关闭mysql连接
				resolve(res)
			}
		});
	})
}

//关闭mysql数据库的函数
function closeMysql(Myconnect) {
	Myconnect.end((err) => {
		if (err) {
			console.log(`mysql关闭失败:${err}!`)
		} else {
			console.log('mysql关闭成功')
		}
	})
}

//导出conMysql函数
exports.conMysql = conMysql

The function to connect to the database has been written and exported, and the next step is to write a simple database query interface in the index.js file just finished

/*
 * @Author: maximing
 * @Date: 2022-12-28 09:06:42
 * @LastEditTime: 2022-12-28 11:23:40
 * @LastEditors: your name
 * @Description: 请添加描述
 * @FilePath: \domysql\src\server\index.js
 */

const express = require('express')
const app = express()

const cors = require('express') //解决跨域问题
app.use(cors())

const bodyParser = require('body-parser')
const multiparty = require('connect-multiparty')
// 处理 x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: true }))
// 处理 mutipart/form-data
app.use(multiparty())
// 处理 application/json
app.use(bodyParser.json())
//导入我们上一步写的连接数据库的函数
const {conMysql} = require('./mysql')
//创建统一的返回报文对象
class Response {
	constructor(isSucceed, msg, code, data) {
		this.isSucceed = isSucceed;
		this.msg = msg;
		this.code = code;
		this.data = data;
	}
}

//一个简单的测试接口
app.get('/test',(req,res)=>{
    res.send('测试用的接口')
})

//一个简单的接口,查询数据库中的信息
app.get('/getUser', (req, res) => {
	let sql = 'select * from test'
	conMysql(sql).then(result => {
		res.send(result)
	})
})

//监听node服务器的端口号
app.listen(3000, () => {
	console.log('恭喜你,服务器启动成功')
})

Post my database table

 Enter the interface address we just wrote in the browser

 ok, so far we have successfully connected to the database and queried the data

3. Write the front-end page

Create a new vue project with vue scaffolding

Post my project directory

 Write a front-end display interface

<template>
	<div>
        <input v-model="user" placeholder="输入用户名查询用户信息">
		<button @click="getUser">点击获取用户信息</button>
	</div>
</template>

<script>
export default {
	name: 'userInfor',
	data() {
		return {
			userInfo: '',
			user: '',
		}
	},
	methods: {

	},
	created() {

	}
}
</script>

<style>
</style>

Next, we also need to install the axios dependency package to send network requests to the backend

npm i axios --save

Secondary encapsulation of axios

Create a new index.js file under the axios folder

import Axios from 'axios'
const instance = Axios.create({
	baseURL: '/api'
})

instance.interceptors.request.use((config) => {
	console.log(config, '发送请求前config信息')
	return config
}, err => {
	return Promise.reject(err)
})

instance.interceptors.response.use((res) => {
	console.log('接受的数据')
	return res.data
}, err => {
	return Promise.reject(err)
})

export default instance

 Create a new api.js file in the same directory for unified processing interface

import request from './index'

//获取用户信息接口
export const getUserInfo = (data) => request.get('/getUserInfo', { params: data })

Add a backend interface for querying information based on user id in the index.js file we just wrote on the node server

/*
 * @Author: maximing
 * @Date: 2022-12-28 09:06:42
 * @LastEditTime: 2022-12-28 11:23:40
 * @LastEditors: your name
 * @Description: 请添加描述
 * @FilePath: \domysql\src\server\index.js
 */

const express = require('express')
const app = express()

const cors = require('express') //解决跨域问题
app.use(cors())

const bodyParser = require('body-parser')
const multiparty = require('connect-multiparty')
// 处理 x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: true }))
// 处理 mutipart/form-data
app.use(multiparty())
// 处理 application/json
app.use(bodyParser.json())
//导入我们上一步写的连接数据库的函数
const {conMysql} = require('./mysql')
//创建统一的返回报文对象
class Response {
	constructor(isSucceed, msg, code, data) {
		this.isSucceed = isSucceed;
		this.msg = msg;
		this.code = code;
		this.data = data;
	}
}


//一个简单的测试接口
app.get('/test',(req,res)=>{
    res.send('测试用的接口')
})

//一个简单的接口,查询数据库中的信息
app.get('/getUser', (req, res) => {
	let sql = 'select * from test'
	conMysql(sql).then(result => {
		res.send(result)
	})
})
//根据前端传过来的id查询数据库中对应的id的信息
app.get('/getUserInfo', (req, res) => {
	let sql = `select * from test where user = '${req.query.user}'`
	conMysql(sql).then(result => {
		let response = new Response(true, '获取成功', 200, result)
		res.send(response)
	}).catch(err => {
		res.status(500).send('数据库连接出错!')
	})
})

//监听node服务器的端口号
app.listen(3000, () => {
	console.log('恭喜你,服务器启动成功')
})

post my directory

 ok, here we have written the front-end interface

Next, we deal with cross-domain issues, why cross-domain, because the local port generally used by the front end is 8080, and the interface used by the node server we just wrote is 3000, different ports appear cross-domain.

We create a new vue.config.js file in the root directory. Generally, vue projects built with scaffolding come with this file

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
})

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        //target 我们要连接的后端地址
        target: 'http://localhost:3000',
        changeOrigin: true, //是否跨域
        pathRewrite: { '^/api': '' }
      },
    },
  },
}

ok, at this point cross-domain is also done, the next step is the front-end and back-end interaction

4. Front-end and back-end interaction

Display the interface call interface on the front end just written

<template>
	<div>
        <input v-model="user" placeholder="输入用户名查询用户信息">
		<button @click="getUser">点击获取用户信息</button>
		<span>{
   
   {userInfo}}</span>
	</div>
</template>

<script>
//导入我们之前写的接口
import { getUserInfo } from '@/axios/api'
export default {
	name: 'userInfor',
	data() {
		return {
			userInfo: '',
			user: '',
		}
	},
	methods: {
        
		async getUser() {
			let res = await getUserInfo({ user: this.user })
			console.log(res, '/api', '获取的用户信息')
			this.userInfo = res.data
		},
	},
	created() {

	}
}
</script>

<style>
</style>

Start the front-end project, start the node service, open the browser to enter any user in the project input database

 Ok, so far the entire front-end and back-end interactions have been completed

Finish

At this point, the whole tutorial is over. If there is any error or understanding in practice, you must go to Baidu to learn new knowledge in time.

Guess you like

Origin blog.csdn.net/weixin_44235659/article/details/128467398