Connecting database through express in Vue

Zhang Hongyun in charge 2021-02-23 14:40:01
connecting database express vue


need vue cli3+,node,express 4.17.1+, MySQL

Xiaobai is one , Write the problems of graduation project , Record it here

I found it on the Internet , And then I wrote it down by myself, and I recorded it here
Original link

If you have any good suggestions, please let me know

One 、 First, create a database

 # Create database
 CREATE DATABASE my\_db\_01
 # Using this database
 USE my\_db\_01
 # Create test table
 CREATE TABLE test(
  id INT AUTO\_INCREMENT PRIMARY KEY, # This field is the primary key and self incrementing
  user\_name VARCHAR(20), # user name
  age TINYINT # Age
 )
 # The test was inserted successfully
 INSERT INTO test(user\_name, age) VALUES('zs', '18')
 # Look at all the data in the table
 SELECT \* FROM test

image

Two 、 initialization vue project

vue create test

download express modular ( Build a simple server )

npm i express

download MySQL modular

npm i mysql

download axios modular

npm i --save axios

perform npm run serve , Can you start it normally

image

3、 ... and 、 Create a simple server and write sql sentence

  1. Create in project root server And then create three .js Documents and a api Folder

image

  1. stay db.js Middle configuration MySQL
// Connection database configuration
 module.exports = {
  mysql: {
  host: 'localhost', // domain name , This is the local domain name
  user: 'root', // MySQL Login username
  password: 'hongyun0808', // MySQL The login password It's usually root
  database: 'my\_db\_01', // Database name to connect to
  port: '3306', // Database port number
  },
 };

image

  1. stay index.js Create a server in
// Use express Create a server
 // Import express modular
 const express = require('express');
 // call express function , Return a database instance
 const app = express();
 // Import routing module
 const userApi = require('./api/userApi');
 // Port number
 const port = 8888;
 // Register global resolution middleware
 app.use(express.json());
 app.use(express.urlencoded({ extended: false }));
 // Register routing module
 app.use('/api/user', userApi);
 // call app.listen() Start the server
 app.listen(port, () => console.log(`Example app listening on port 8888!`));

image

  1. slqMap.js write in sql sentence
// todo sql The statement is called later
 module.exports = {
  user: {
  // ? Place holder The data is automatically filled in later
  add: 'insert into test(user\_name, age) values(?, ?)',
  get: 'select \* from test',
  },
 };

image

  1. api/userApi.js Test use api example
// Test use api example
 var models = require('../db');
 var express = require('express');
 var router = express.Router();
 var mysql = require('mysql');
 var $sql = require('../sqlMap');
 // Connect to database
 var conn = mysql.createConnection(models.mysql);
 conn.connect();
 var jsonWrite = (res, ret) => {
  if (typeof ret === 'undefined') {
  res.json({
  code: '1',
  msg: ' operation failed ',
  });
  } else {
  res.json(ret);
  }
 };
 // Add user interface
 // POST request
 router.post('/addUser', (req, res) => {
  var sql = $sql.user.add;
  var params = req.body;
  console.log(params);
  // ! [params.username, params.age] Automatically fill in before ? Inside
  conn.query(sql, [params.user\_name, params.age], (err, result) => {
  if (err) return console.log(err);
  if (result) {
  jsonWrite(res, result);
  }
  });
 });
 // GET request
 router.get('/getUser', (req, res) => {
  let sql = $sql.user.get;
  let params = req.query;
  console.log(params);
  conn.query(sql, (err, result) => {
  if (err) {
  console.log(err);
  }
  console.log(res, result);
  });
 });
 module.exports = router;
  1. use cmd perhaps PowerShell open server File execution node index

This indicates that the startup is successful
image
Be careful : Here, do not shut down the server after it is started , Otherwise, we have to make a mistake in the back , Report this error and start the server
image

Four 、 To write vue The test file

For the convenience of testing, directly in HelloWorld.vue It's a test in here

image

<template>
<div class="hello">
<h1>{{ msg }}</h1>
<form>
<input type="text" name="username" v-model="userName" /> <br />
<input type="text" name="age" v-model="age" /> <br />
<a href="javascript:;" @click="addUser"> Submit </a> <br />
<a href="javascript:;" @click="getUser"> obtain </a>
</form>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
userName: "",
age: "",
};
},
props: {
msg: String,
},
methods: {
addUser() {
let user_name = this.userName;
let age = this.age;
this.$http
.post(
"/api/user/addUser",
{
user_name,
age,
},
{}
)
.then((response) => {
console.log(response);
});
},
getUser() {
// ! It can't be printed in the browser console , But on the server side (cmd Medium or power shell) It can be printed out , You can save the value in the server vuex in
this.$http
.get("/api/user/getUser")
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
h3 {
margin: 40px 0 0;
}
a {
color: #42b983;
}
</style>

5、 ... and 、 Setting up proxy and cross domain

Direct execution npm run serve Will report a mistake

  1. This is due to direct access to 8080 port , It's not accessible , So here we need to set up the proxy forwarding map .

image

Create... In the root directory vue.config.js file , And write the following

The specific contents are as follows :

image

Write content :

module.exports = {
  devServer: {
  proxy: {
  '/api': {
  target: 'http://127.0.0.1:8888/api',
  changeOrigin: true, // To solve the cross domain
  pathRewrite: {
  '^/api': '',
  },
  },
  },
  },
 };

image

  1. stay main.js Add
import axios from 'axios';
 Vue.prototype.$http = axios;

image

6、 ... and 、 Success page

When finished, close the editor and open it again npm run serve

POST request

Click on the submit

HTML page

image

power shell page

image

database page

image

GET request

Click to get

HTML And databases have no effect

power shell page

image

版权声明
本文为[Zhang Hongyun in charge]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223143906270D.html

  1. 对前端异常window error捕获的全面总结
  2. A comprehensive summary of front end exception window error capture
  3. 成功解决Problem while trying to mount target]\“. HTTP response code is 400
  4. Problem while trying to mount target] \ ". HTTP response code is 400
  5. 放弃okhttp、httpClient,选择了这个牛逼的神仙工具!贼爽
  6. 前端面试每日 3+1 —— 第679天
  7. How to add elements at the beginning of an array in JS?
  8. Give up okhttp and httpclient and choose this awesome immortal tool! Thief Shuang
  9. Front end interview daily 3 + 1 - day 679
  10. 【2021 第一期】日常开发 26 个常见的 JavaScript 代码优化方案
  11. Daily development of 26 common JavaScript code optimization schemes
  12. 前端的字符串时间如何自动转换为后端Java的Date属性,介绍springMVC中如何解决时间转换问题
  13. How to automatically convert the front-end string time to the back-end Java date attribute, and how to solve the time conversion problem in spring MVC are introduced
  14. 前端面试常考题:JS垃圾回收机制
  15. ReactDOM.render串联渲染链路(一)
  16. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  17. 粗涉Webpack
  18. Frequently asked questions in front end interview: JS garbage collection mechanism
  19. ReactDOM.render Serial rendering link (1)
  20. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!
  21. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  22. About webpack
  23. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!
  24. 详解vue静态资源打包中的坑与解决方案
  25. 一篇搞懂TCP、HTTP、Socket、Socket连接池
  26. 字节跳动2021前端技术岗发布+最新内部面试题
  27. Detailed explanation of Vue static resource packaging and Solutions
  28. Understanding TCP, HTTP, socket, socket connection pool
  29. 2008-2021 front end technical post release + latest internal interview questions
  30. 4. Vue基本指令
  31. 4. Vue basic instruction
  32. Java 发起 http 请求
  33. Java initiates HTTP request
  34. 网站由http升级为https图文教程
  35. Upgrade the website from HTTP to HTTPS
  36. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  37. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!
  38. 混合开发入门 Vue结合Android/iOS开发仿京东项目App
  39. Hybrid development entry Vue combined with Android / IOS to develop app imitating Jingdong project
  40. 无缝对接 Tableau,这家月活跃用户 5000+ 的大型银行如何实现自助式分析?
  41. Are airpods still the strongest? Horizontal evaluation of 4 true wireless headphones
  42. Seamless connection with tableau, how can this large bank with 5000 + active users realize self-service analysis?
  43. react-native版文字跑马灯
  44. React native text running lantern
  45. Java、JavaScript、C、C++、PHP、Python都是用来开发什么?
  46. What are Java, JavaScript, C, C + +, PHP and python used to develop?
  47. this.byId(SupplierForm).bindElement in SAP UI5
  48. SAP UI5 JavaScript文件的lazy load - 懒加载
  49. this.byId (SupplierForm).bindElement in SAP UI5
  50. Lazy load lazy load of SAP ui5 JavaScript files
  51. "Gnome 3" - interface elements, desktop components, part names (learning notes) @ 20210223
  52. How to connect the ground gas to the micro front end?
  53. How to transform single / micro service application into serverless application
  54. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  55. Seven array methods for JavaScript you need to master in 2021
  56. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  57. Seven array methods for JavaScript you need to master in 2021
  58. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  59. Seven array methods for JavaScript you need to master in 2021
  60. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库