Why should front-end developers learn Node? Will it be used in real development?
The answer is yes. Node.js is something front-end engineers must learn if you want to make the most of software development.
Node.js isn’t hard to learn, and it can be very rewarding. This article is intended for node.js based users
Project creation
1. Install koA-Generator globally
npm install koa-generator -g
Copy the code
A quick generator similar to the Express project has a basic template to work with
The installation is complete
2. Generate the KOA project
Use the KOA + project name. To generate
Basic Project Directory
3. Start the project
Here we need to install the dependencies first
npm install
Copy the code
Then use NPM Run Start to start the project
Modify project Files
You can see the generated directory and files here. App.js is the entry file
We modify app.js as follows.
const Koa = require('koa') / / import koa
const app = new Koa()
// const views = require('koa-views'
const json = require('koa-json') // This is required for json formatting
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser') // Get the data submitted by the post ctx.requset.body
const logger = require('koa-logger') / / log
const mysql = require('./utils/db.js') // Import the js file connected to mysql
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes: ['json'.'form'.'text']
}))
app.use(json())
// Console logs
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
// app.use(views(__dirname + '/views', {
// extension: 'pug'
// }))
// Console logs
app.use(async (ctx, next) => {
const start = new Date(a)await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)})// Import routes
const index = require('./routes/index')
const users = require('./routes/users')
// Use routing
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
// error-handling
app.on('error'.(err, ctx) = > {
console.error('server error', err, ctx)
});
app.listen(3000.() = > {
console.log('http://localhost:3000')})module.exports = app
Copy the code
Modified file directory
Under utils is the tools folder. Db. Js js file for connecting data. Public is the static file. Config > default.js is the default configuration file
Mysql > Install mysql
The download address is as follows: mysql website download link
Download mysql to your own computer
Use mysql in your project
npm install mysql
Copy the code
Using Navicat
Next we use a very good mysql visualization software Navicat Premium (macOs), Navicat 12 (Windows) if you need software resources please contact us
Open the software and click New Connection below
After creating a new connection. Enable the connection. Create a table. Let’s say we set the name of this table to lists
Insert content into the database
Open the file directory and choose Config > default.js
// default.js
// Set the configuration file
const config = {
// Database configuration
database: {
DATABASE: 'test'./ / table name
USERNAME: 'root'./ / user name
PASSWORD: '12345678'./ / password
PORT: '3306'.// Connection port
HOST: 'localhost' //host}}module.exports = config
Copy the code
Open the file directory utils > db.js
var mysql = require('mysql'); // Import the installed mysql. NPM install mysql
var config = require('.. /config/default.js') // Import the location file
var pool = mysql.createPool({ // Create a mysql connection
host: config.database.HOST,
user: config.database.USERNAME,
password: config.database.PASSWORD,
database: config.database.DATABASE
});
// Here we encapsulate a query method to operate on local data
// The basis for adding, deleting, modifying and checking the database
let query = (sql, values) = > {
return new Promise((resolve, reject) = > {
pool.getConnection((err, connection) = > {
if (err) {
reject(err)
} else {
connection.query(sql, values, (err, rows) = > {
if (err) {
reject(err)
} else {
resolve(rows)
}
connection.release()
})
}
})
})
}
exports.query = query
Copy the code
Open the Routes > index.js route file
const router = require('koa-router') ()/ / import koa - the router
const mysql = require(".. /utils/db") / / import db. Js
router.get('/'.async (ctx, next) => {
ctx.body = {
code: 200.data: [{
name: "orange".age: 18}].message: "Query succeeded"
}
})
router.get('/string'.async (ctx, next) => {
ctx.body = 'koa2 string'
})
router.post('/post'.async (ctx, next) => {
console.log(ctx.request.body);
ctx.body = {
code: 200.message: "Add successful"
}
})
router.get('/mysql'.async (ctx, next) => {
let arr = [{
id: 7.name: "orange".age: 21
}, {
id: 9.name: "andy".age: 21
}]
arr.map(async (val) => {
let sql = `insert into lists set name=? ,age=? `
// const sql = `select * from lists`
// Insert the contents of the newly created ARR into the table
await mysql.query(sql, [val.name, val.age]).then(async (res) => {
ctx.body = {
"code": 1
}
}).catch(() = > {
console.log("Add error"); })})})module.exports = router
Copy the code
When we access the/path, we can see the data returned from Postman
When we access /mysql, we can see that the content is inserted into the database
Note: This article only briefly describes mysql connection and general usage. Let the new person can understand more detailed tutorial suggestions according to the video to learn effectively