introduce

This is a blog of my own local blog….

technology

React + ANTD + TS is used in the front end, Node + KOa is used in the back end, and mysql is used in the database

The front end

The installation

  • Create a file
create-react-app demo --typescript
Copy the code
  • The introduction of the UI (antd)
yarn add antd
Copy the code

Modify SRC/app.css to introduce antD at the top of the file

@import '~antd/dist/antd.css';
Copy the code
  • Install important modules

Axios (send a request)

npm install @types/axios
Copy the code

Node-sass (use Sass instead of CSS)

npm install node-sass
Copy the code

Possible problems

  • When the “–isolatedModules” flag appears

Add isolatedModules:false in tsconfig.json

  • The React module cannot be found

Add “noImplicitAny”: false to tsconfig.json

Main functions

  • landing
  • The article lists
  • give a like

Wrap AXIos

export default function http({url,method='GET',data={}}){
    return new Promise((resolve,reject)=>{
        axios({
            url:`${baseUrl}${url}`,
            method,
            data
        }).then(res=>{
            if(res.data.success){
                resolve(res.data.data)
            }else{
                reject(res.data.message)
            }
        }).catch(err=>{
            console.log(err)
            reject(err)
        })
    })
}
Copy the code

The mysql database

download

Go to the mysql official website to download the corresponding mysql

The command

Linked database

mysql -uroot -p
Copy the code

restart

mysql.server restart

Copy the code

Start the

mysql.server start

Copy the code

stop

mysql.server stop

Copy the code

The back-end koa

The installation

npm install koa
Copy the code

The introduction of

const koa=require('koa');
const app=new koa();
Copy the code

Koa2 handles all requests asynchronously

app.use(async (ctx, next) => { await next(); ctx.response.type = 'text/html'; ctx.response.body = '<h1>Hello, koa2! </h1>'; });Copy the code

CTX encapsulates response and Request, which can be accessed through ctx.request and ctx. Response, and next is an asynchronous function for the next operation

Koa registers async asynchronous functions with app.use() each time it receives an HTTP request, passing in CTX and next parameters

Each async function is a middleware. Use await next() to synchronize asynchron, so the order of middleware is important, i.e. the order of app.use() is important.

koa-router

The installation

npm install koa-router
Copy the code

Koa-router registration request, parameters can be obtained through ctx.params.name

app.use(router.routes())

koa-bodyparser

The installation

npm install koa-bodyparser
Copy the code

Koa-bodyparser parses the body parameter of post requests

Koa-bodyparser must be a Router before being registered on the app

const bodyParser = require('koa-bodyparser');
app.use(bodyParser())
Copy the code

koa-cors

The installation

npm install koa-cors
Copy the code

It mainly solves cross-domain problems

const cors=require('koa-cors')

app.use(cors())
Copy the code

Or you can add it manually

app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With')
    ctx.set('Access-Control-Allow-Origin', 'http://localhost:3000');
    ctx.set('Access-Control-Allow-Methods', 'PUT,DELETE,POST,GET');
    ctx.set('Access-Control-Allow-Credentials', true);
    ctx.set('Access-Control-Max-Age', 3600 * 24);
}),
Copy the code

Koa connection mysql

Mysql installation

npm i mysql

Copy the code

The connection

const mysql=require('mysql'); Const config={host:"localhost", user:" username ", password: "password ", database:" database ", port: "port ", Whether multipleStatements: true / / support multiple connections} const pool = mysql. CreatePool (config); Let query = (SQL, values) => {return new Promise((resolve, reject) => {pool.getConnection((err, err)) Connection) => {// Connect to database if (err) {reject(err)// Connect to database failed} else {connection.query(SQL, values, (err, If (err) {reject(err)} else {resolve(rows)} Connection.release ()})})})}; module.exports={ query }Copy the code

The function point

landing

Front-end user name and password

The back-end

const db=require('.. /db/index') exports.login=async ctx=>{ const {name,password}=ctx.request.body const sql='SELECT * FROM t_user WHERE name=? and password=? '; const value=[name,password]; await db.query(sql,value).then(res=>{ if(res.length>0){ ctx.session.user=name console.log(ctx.session.user) Ctx.response.body ={success:true, data:res[0]}}else{ctx.response.body={success:false, message:' login failed '}}})}Copy the code

Gets a list of articles and fuzzy queries by criteria

const db=require('.. /db/index') exports.articleList=async ctx=>{ const {searchData}=ctx.request.body; const sql='SELECT * FROM t_article_list WHERE title LIKE "%'+searchData+'%"'; await db.query(sql).then(res=>{ console.log(res) ctx.response.body={ success:true, data:res } }) }Copy the code

give a like

const db=require('.. /db/index') exports.agree=async ctx=>{ const {article_id}=ctx.request.body const sql='update t_article_list set likeCount=likeCount+1 where article_id=? ' const value=[article_id]; Await db.query(SQL,value).then(res=>{ctx.response.body={success:true, message:' like '}})}Copy the code

For detailed code, please check out my warehouse, welcome star ~ ~