Environment set up

1. Install the Node environment by yourself

2. Install express globally

npm install -g express

3. Create the Express project folder

Express create projects default to the Jade template engine, if using another engine, use command switch

Express node_demo -e (select EJS template) // Add -e to the end of the project name to create a. Ejs template file with the same syntax as HTML

Open our project in vscode as follows:

For those who are not used to looking at ejS, you can change it to HTML as follows:

Then you also need to create a new index.html in views and error error.html

The installation depends on NPM install

Start the project NPM start

Listen to the bin/ WWW file, default port 3000, can be changed in the WWW file, open a browser, type localhost:3000

At this point we can see that the page displays the content defined in index. HTML

Because every modification needs to be restarted, which is quite troublesome, there is a plug-in nodemon, which can be restarted automatically

npm install nodemon

Change the code in package.json file to:

"start": "nodemon ./bin/www"

Connect to MySQL database

  1. To install mysql

Mysql > install db.config.js; mysql > install db.config.js; mysql > install db.config.js;

Module. exports = {host: 'localhost', // server address user: '*****', // mysql user name password: '* * * * * * * * * *', / / mysql user password port: '3306', / / port database: 'onepiece, / / database name}Copy the code
// db.js var mysql = require('mysql') var dbConfig = require('./db.config') module.exports = { query: Function (SQL, params, callback) {function (SQL, params, callback) { Var Connection = mysql.createconnection (dbConfig) connection.connect(function (err) {if (err) {throw err Connection. query(SQL, params, function (err, results, Callback && callback(json.parse (json.stringify (results)), if (err) {throw err} Json.parse (json.stringify (fields))) // Stop linking to a database. Connection. end(function (err) {if (err) {console.log(' Failed to close database connection! ') throw err } }) }) }) }, }Copy the code

We can then add the following code to the users file in the Routes directory:

var db = require('.. /conf/db') router.get('/userList', (req, res, next) => {// SQL query db. Query ('SELECT * FROM user', [], Function (results, fields) {// Return res.json({results})})Copy the code

Open a browser to http://localhost:3000/users/userList

This is a simple nodeJS + Express connection to the database

Afterword.

Install Navicat Premium

Link: pan.baidu.com/s/1aa0p4pHZ…

Extraction code: Navi

MySQL installation

Link: pan.baidu.com/s/18o-afzb3…

Extraction code: MSQL