A similar ThinkPHP the Node.js framework --QuickNode

QuickNode

Node.js QuickNode from the beginning, so restful interface development easier!

PHP's MVC

As a former PHP developer, I have had more than three years thinkphp experience, it was the first I learned PHP MVC framework contacted. ThinkPHP is also regarded as the most popular PHP framework of the bar, I say to the frame left me the deepest impression is created in a simple and convenient method when a new controller and new, as well as her classic / Controller / Action routing mode.

After the graduation, my work turned to the front, but as a full-stack, I am still responsible for some of the back-end server development and operation and maintenance, re-use the Node, I gradually fell in love with this door concise and wonderful language, especially after ES7 standard, TS addition, let me JS, TS family had a strong dependence, whether it is doing now the site of API, mobile phone app or script I will be the preferred JS.

Node has had experience in the development of children's shoes should know, Node web framework although more simple, the volume is much smaller, but also accompanied by a modular package brings messy, messy code organization, cumbersome configuration, when you download after the express request still needs to manually configure the interface routing, very troublesome. For just switch node from the camp php friends need some learning costs. And it makes me a habit of using MVC framework of PHP programmers represent very large head. At this point the most urgent needs is a framework for PHP programmers are accustomed to, similar to ThinkPHP this.

For this reason I specifically use Node.js developed a simple MVC framework ThinkPHP imitation, saying that he is in fact, not strictly MVC, which is more like a cargo version of a node ThinkPHP, has the basic functions ThinkPHP, along with a restful of Interface style.

start using

I posted a QuickNode in github, this is Node MVC framework I ThinkPHP of the imitation. MVC framework but not in the strict sense, so I would not be so defined framework.

QuickNode of use and ThinkPHP exactly the same.

Installation Node

Install the latest version of node.js, group exercise, not go into details, it is recommended to download the official website. https://nodejs.org

git clone code base frame

git clone https://github.com/devilyouwei/QuickNode.git

Installation package

Downloaded into the project directory

npm install

Well, if that is not being given all outsourcing installed.

MySQL Configuration

Enter the Config directory, configuration db.json to connect mysql, it can be locally or remotely of mysql server.

start using

node ./Server.js

Debugging using supervisor

Recommended supervisor, because node stupid, modify the code to be re-run every command, supervisor can automatically monitor changes in the code, once modified the code to automatically run the latest code to facilitate debugging

npm -g install supervisor

supervisor ./Server.js

Successful operation
Case

Sample

Here are some cases, novice experience with you how to create a API, and how to access this API, how to connect to the database, if you are a PHP programmer, you will find it and ThinkPHP really very similar.

Creating the Controller

First, create a file in the Controller directory, for example, Test.js, this is a JS class file, it is also a controller.

code show as below:

class Test{
    static async test(req,res){
        return res.json({status:1,data:'test data',msg:'Successful data loaded'})
    }
}
module.exports=Test

Continued open browser to access: HTTP: // localhost: 3000 / the Test / the Test

Here Insert Picture Description
The new controller accesses a success.

Connect to the database

Before connecting to the database, please configured db.json file, make sure to get permission to access the database.

Next, an exemplary embodiment of a database connection:

const db = require('./private/DB.js')
const $ = require('../private/tool.js')

class Config{
    static async query(req,res){
        let data = await db.query('select * from languages')
        return res.json({status:1,data:data,msg:'languages'})
    }
    static async insert(req,res){
        let body=req.body // 获取post和get传来的数据
        // 新增
        let data={
               title:body.title,
               rank:body.rank,
               time:$.date2stamp()
        }
        // 插入数据
        let id = await db.insert('type',data)
        if(id>0) return res.json({status:1,msg:'插入成功'})
        else return res.json({status:0,msg:'插入失敗,數據寫入錯誤'})
    }
}
module.exports=Config

Refer to play more database: https://www.npmjs.com/package/mysql

Front-end parameter passing

GET and POST QuickNode allow transmission parameters, parameter passing POST form formdata recommended, distal need new FormData () to initialize a data format formdata.

Whether GET or POST data are acquired in req.body in.

const db = require('./private/DB.js');

class Config{
    static async index(req,res){
        let id = req.body.id
        return res.end(`Id is:${id}`)

    }
}
module.exports=Config

Here Insert Picture Description

Reference front-end code (vue):

import { Toast, Dialog } from 'vant'
import Mobile from 'mobile-detect'
import axios from 'axios'
import {i18n} from './plugins/i18n.js'

//const URL = 'http://localhost:3000' // 測試服
const URL = 'https://api.qbite.us' // 正式服
export default {
    // use axios
    async post (ctl, act, data = {}, load = false) {
        if(!ctl || !act) throw new Error('no controller or action')
        let url = `${URL}/${ctl}/${act}`
        let form = new FormData()
        for (let i in data) form.append(i, data[i])

        form.append('user', JSON.stringify(this.getUserInfo()))
        if (load) this.loading(load)
        try{
            let res = await axios({
                method: 'post',
                headers: { 'content-type': 'application/x-www-form-urlencoded' },
                url: url,
                data: form,
                responseType: 'json',
                changeOrigin: true // 允许跨域
            })
            res = res.data
            res.status = parseInt(res.status) || 0
            if(res.status == -1){
                localStorage.removeItem('user')
                await this.alert(i18n.t('noLogin'))
                return location.replace(`/?did=${localStorage.getItem('did')}`)
            }
            return res
        }catch(e){
            throw e
        }finally{
            if (load) this.loading(false)
        }
    },
    
    // use fetch, it can't compatible with old browser
    async post2(ctl='',act='',data={},load=false){
        if(!ctl || !act) throw new Error('no controller or action')
        let url = `${URL}/${ctl}/${act}`
        // 表單信息
        let form = new FormData()
        for (let i in data) form.append(i, data[i])
        // 餐桌ID
        form.append('did',localStorage.getItem('did')) // 桌子

        let request = new Request(url, {method: 'POST', body: form})
        try {
            if (load) this.loading(true)
            let res = await fetch(request).then(res => res.json())
            res.status = parseInt(res.status) || 0
            return res
        } catch (err) {
            throw err
        } finally {
            if (load) this.loading(false)
        }
    }
}

Post here we describe two methods, one using axios, using the latest fetch API, no matter what kind of data should be transmitted using formdata format.

postscript

QuickNode is open source out of the Q-tech LLC (US) company's business project "Qbite" in a back-end frame, the frame itself is very lean and light, suitable for restful interface mode is similar to many domestic traditional MVC framework.

Qbite ordering system is under a US online and offline, back-end framework that is currently used to support QuickNode. QuickNode will be tested and updated in the continued use of Qbite.

The MVC framework has not yet been added to Model a follow-up project will be added Model, you can fork small partners to provide programs and projects of our contribution.

Thank you for the support of the QuickNode, like friends, please help look under the star, your star is our driving force, I'm glad you use our project.

https://github.com/devilyouwei/QuickNode

Guess you like

Origin www.cnblogs.com/devilyouwei/p/11946711.html