1. 程式人生 > >node.js從入門到放棄(一)

node.js從入門到放棄(一)

主鍵 data timestamp insert 代碼 了解 javascrip ice where

以下內容全是我個人理解寫出,如有不對,請立刻練習本人進行更改。以免被剛入門的被我帶入坑裏。

—node是什麽?我想大家應該都知道。

node是前端未來幹掉後端的一種語言,是用JavaScript來編寫後端代碼的一種語言。前端走後端的路讓後端無路可走。是前端人員走向全棧開發的一條路。

—學習node要掌握什麽呢?學習它就需要掌握一下幾個方面,這是我現在學習的時候需要掌握的東西,算是很基本的東西了。

一、node的安裝

二、數據庫的安裝和使用(sql命令)

三、node最底層基本寫法

四、koa框架

五、Sequelize功能模塊使用

六、讀寫文件

node的安裝在這裏就不講了,網上一搜就都能搜到的,不想搜也可以點擊這個連接,去看下node安裝這些都有詳細的介紹。

數據庫的安裝在網上也能夠搜索到,安裝數據庫可以看下這個博客,這裏寫的挺詳細的,從安裝數據庫到navicat MySQL的安裝都有 查看請點擊這裏↓↓↓↓↓↓↓

sql的命令離不開增刪改查

mydb:數據庫名

user:表名

text:對應的屬性名

2:要插入的數據

id:主鍵

age:對應的屬性

增: INSERT INTO `mydb`.`user` (`text`) VALUES (‘2‘);

刪:DELETE FROM user WHERE id=1

改:UPDATE `mydb`.`user` SET `age`=‘22‘ WHERE `id`=‘1‘;

查:select * from user

以上就是數據操作的主要四個,其他命令可以百度一下,一抓一大把。

接下來進入最主要的地方了,開是接觸放棄的地方了,底層的基本用法

+開始需要把數據庫放進去才能夠使用

$ cnpm install mysql

 接下來引入你本地的數據庫

// 連接數據庫
var mysql      = require(‘mysql‘);
var connection = mysql.createConnection({
host     : ‘localhost‘,
user     : ‘root‘,
password : ‘123456‘,
database : ‘node‘
}); 

 接下來開始搗鼓你的數據庫(我的數據庫放了一下的數據名)

技術分享圖片

接下來對下面的數據進行操作(用上面已經連接上的數據庫)

node底層寫法:

var http = require(‘http‘);
// 連接數據庫
var mysql      = require(‘mysql‘);
var connection = mysql.createConnection({
host     : ‘localhost‘,
user     : ‘root‘,
password : ‘123456‘,
database : ‘node‘
}); 
// 請求下數據庫
connection.connect();   
var http = require("http");
var url = require("url");
// 調用方法
function start() {
  function onRequest(request, response) {}
  http.createServer(onRequest).listen(8888);
 端口號是8888去進行請求 } start();

  新增數據方法

// 新增數據
const hello = function (response, data) {
  connection.query(`INSERT INTO log  (content, summary, user, day) VALUES ("${data.content}", "${data.summary}", "${data.user}","${data.day}");`, function (error, results, fields) {
    if (error) throw error;
      // 請求成功,返回格式
      response.writeHead(200, {"Content-Type": "application/json"});
      // 返回給頁面的數據
      response.write(JSON.stringify(results.insertId));
      // 請求結束
      response.end();
  });
}

  獲取列表

//  獲取列表
const hello2 = function (response, data) {
  connection.query(`select * from log`, function (error, results, fields) {
    if (error) throw error;
      response.writeHead(200, {"Content-Type": "application/json"});
      response.write(JSON.stringify(results));
      response.end();
  });
}

  刪除事件

// 刪除id=4
const hello4 = function (response,data){
  console.log(data)
  connection.query(`DELETE FROM log WHERE id=${data.id}`,function (error,results,fields) {
    if (error) throw error;

    response.write("ok");
    response.end();
  })
}

  分頁寫法

// 分頁寫法
const hello3 = function (response, page, size) {
  console.log(‘page, size‘, page, size)
  connection.query(`select * from log  limit ${size} offset ${(page-1)*size} `, function (error, results, fields) {
    if (error) throw error;
      response.writeHead(200, {"Content-Type": "application/json"});
      response.write(JSON.stringify(results));
      response.end();
  });
}

  調用的話直接調用方法就可以(這裏還需要註意是get請求還是post請求)

// 調用方法
function start() {
  function onRequest(request, response) {
    // /hello
    var pathname = url.parse(request.url).pathname.split(‘/‘);
    // /hello3/1/10
    // 接收數據
    if (request.method === ‘POST‘) {
      request.on(‘data‘, function(data) {
        // 把數據轉換成json格式
        let data1 = JSON.parse(data.toString())
        console.log(‘data: ‘, data1.toString(), data1)
        // 接收到的接口調用什麽方法
        switch(pathname[1]) {
          case ‘hello‘: { hello(response, data1) } break;
          case ‘hello2‘: { hello2(response, data1) } break;
          case ‘hello3‘: { 
            // 用拼接的方式(get)獲取數據方法
            // let page = pathname[2]
            // let size = pathname[3]
            // console.log(pathname)
            // 用接收體來調用數據(post)
            hello3(response, data1.page, data1.size) 
          } break;
          case ‘hello4‘: { hello4(response, data1) } break;
          // 調用weitch方法
          default: response.end();
        }
      })
    }

  完整的使用代碼

var http = require(‘http‘);
// 連接數據庫
var mysql      = require(‘mysql‘);
var connection = mysql.createConnection({
host     : ‘localhost‘,
user     : ‘root‘,
password : ‘123456‘,
database : ‘node‘
}); 
// 請求下數據庫
connection.connect();   
var http = require("http");
var url = require("url");
// 新增數據
const hello = function (response, data) {
  connection.query(`INSERT INTO log  (content, summary, user, day) VALUES ("${data.content}", "${data.summary}", "${data.user}","${data.day}");`, function (error, results, fields) {
    if (error) throw error;
      // 請求成功,返回格式
      response.writeHead(200, {"Content-Type": "application/json"});
      // 返回給頁面的數據
      response.write(JSON.stringify(results.insertId));
      // 請求結束
      response.end();
  });
}
//  獲取列表
const hello2 = function (response, data) {
  connection.query(`select * from log`, function (error, results, fields) {
    if (error) throw error;
      response.writeHead(200, {"Content-Type": "application/json"});
      response.write(JSON.stringify(results));
      response.end();
  });
}
// 刪除id=4
const hello4 = function (response,data){
  console.log(data)
  connection.query(`DELETE FROM log WHERE id=${data.id}`,function (error,results,fields) {
    if (error) throw error;

    response.write("ok");
    response.end();
  })
}
// 分頁寫法
const hello3 = function (response, page, size) {
  console.log(‘page, size‘, page, size)
  connection.query(`select * from log  limit ${size} offset ${(page-1)*size} `, function (error, results, fields) {
    if (error) throw error;
      response.writeHead(200, {"Content-Type": "application/json"});
      response.write(JSON.stringify(results));
      response.end();
  });
}

// 調用方法
function start() {
  function onRequest(request, response) {
    // /hello
    var pathname = url.parse(request.url).pathname.split(‘/‘);
    // /hello3/1/10
    // 接收數據
    if (request.method === ‘POST‘) {
      request.on(‘data‘, function(data) {
        // 把數據轉換成json格式
        let data1 = JSON.parse(data.toString())
        console.log(‘data: ‘, data1.toString(), data1)
        // 接收到的接口調用什麽方法
        switch(pathname[1]) {
          case ‘hello‘: { hello(response, data1) } break;
          case ‘hello2‘: { hello2(response, data1) } break;
          case ‘hello3‘: { 
            // 用拼接的方式(get)獲取數據方法
            // let page = pathname[2]
            // let size = pathname[3]
            // console.log(pathname)
            // 用接收體來調用數據(post)
            hello3(response, data1.page, data1.size) 
          } break;
          case ‘hello4‘: { hello4(response, data1) } break;
          // 調用weitch方法
          default: response.end();
        }
      })
    }

    // Get
    if (request.method === ‘GET‘) {
      response.end(‘aaaaa‘);
    }
  }
 
  http.createServer(onRequest).listen(8888);
}
start();

  

開始化簡模式。學習使用koa框架

安裝koa

npm intall koa2
npm intall koa-router

  在頁面引入

const Koa = require(‘koa‘)
const bodyParser = require(‘koa-bodyparser‘)
const Router = require(‘koa-router‘)

  來個簡單例子

const Koa = require(‘koa‘);
//引入koa
  const app = new Koa();
  //方法放到app下
  app.use(async ctx => {
    ctx.body = ‘Hello World‘;
  });
  //執行方法
  app.listen(3000);
//app創建端口號

  koa主要的就是request的請求方法,response響應,因為太多就不在這講了,想了解的 戳這裏↓↓↓↓↓

app.use(async ctx => {
    console.log(ctx.request.href)
//獲取到地址,換個方法就可以獲取前臺傳得數據
    ctx.response.body = "aaaaa"
//返回值
});

  來上面的去看文檔慢慢敲就行了,Sequelize功能模塊使用來講一下

var Sequelize = require(‘sequelize‘);
var mysql = new Sequelize(‘node‘, ‘root‘, ‘123456‘, {
    host: ‘localhost‘,
    dialect: ‘mysql‘,
    pool: {
        max: 5,
        min: 0,
        idle: 10000
    },
})

  看數據庫的導入方式就不一樣了,接下來我們使用的可能多數都是這樣的,樣式了。

//數據表裏面的內容
var Log = mysql.define(‘log‘, {
    id: {
        primaryKey: true,
        type: Sequelize.INTEGER,
    },
    content: Sequelize.STRING,
    summary: Sequelize.STRING,
    user: Sequelize.STRING,
    day: Sequelize.STRING,
  }, {
    freezeTableName: true, // Model 對應的表名將與model名相同
    timestamps: false
  });

  使用方法查詢數據

Log.findAll({
        where: {
            $and: [
                { id: {gt: 32} },
                 //大於多少
                { id: {lt: 35} }
                //小於等於多少
            ]
        },
        raw: true
    }).then(res => {
        console.log(res.length)
    //一共多少條
    for(var i=0 ;i<res.length;i++){
//遍歷出來顯示
        Log.create(
        {
            content: res[i].content,
            summary: res[i].summary,
            user: res[i].user,
            day: res[i].day
        }
    )
    }
    
})

  整體使用

const main = async function() {
//查詢所有
    let res = await Log.findAll({
        raw: true
    })
//寫入
    let newDatas = res.map(item => ({
        a: item.content,
        b: item.summary,
        c: item.user,
        d: item.day,
    }))
//往新表裏插入多條數據
    await Aaa.bulkCreate(newDatas)
//刪除數據
    await Aaa.destroy({ where: {
        id: 2
    }})
//修改數據
    await Aaa.update({
        a: ‘item.content‘,
        b: ‘item.summary‘,
        c: ‘item.user‘,
        d: ‘item.day‘,
    }, {
        where: {
            id: 3
        }
    })
}

main()

  接下來進行三軍會師,用三種方法寫成最簡單的代碼來調用數據

開始在app文件中

const Koa = require(‘koa‘)
const bodyParser = require(‘koa-bodyparser‘)
const router = require(‘./controllers‘)
//引入使用包
const app = new Koa()
app.use(bodyParser())
//調用koabadyparser方法
app.use(router.routes())
app.listen(3000)
//引入文件,創建端口

  在controllers文件中寫入方法並進行調用

const Router = require(‘koa-router‘)
const router = new Router()
const services = require(‘./services‘)

//查詢所有數據
router.get(‘/‘, async (ctx, next) => {
    let res = await services.hello1()
    ctx.body = res
});
//返回值hello world
router.get(‘/hello‘, (ctx, next) => {
    ctx.body = "hello world"
});
//新增數據
router.post(‘/hello2‘, async (ctx, next) => {
    let obj = ctx.request.body
    let res = await services.hello2(obj)
    let eee = {
        content : res.content,
        summary : res.summary
    }
    ctx.body = {
        statusCode: 200,
        result:eee
    }
})
//刪除數據
router.post(‘/hello3‘, async (ctx, next) => {
    let obj = ctx.request.body
    let res = await services.hello3(obj)

    ctx.body = {
        statusCode: 200,
    }
})
//查詢數據
router.post(‘/hello4‘, async (ctx, next) => {
    let obj = ctx.request.body
    let res = await services.hello4(obj)
    ctx.body = res
})
//更改數據
router.post(‘/hello5‘, async (ctx, next) => {
    let obj = ctx.request.body
    let res = await services.hello5(obj)
    ctx.body = res
})
//調用
module.exports = router

  在services.js文件中

const Log = require(‘./models‘)

const hello = async function (obj) {
    //放個查詢方法
    let logs = await Log.Log.findAll({
        where: {
            $and: [
                {id: { $gt: obj.id }},
                {id: { $lte: obj.css }}
            ]
        }
    })

    return logs
}
//查詢所有數據大於0的
const hello1 = async function () {
    let loge = await Log.Log.findAll({
        where: {
            id: { gt: 0},
        }
    })

    return loge
}
//新增數據
const hello2 = async function (obj) {
    let loge = await Log.rizhi.create({
            content:obj.content,
            summary:obj.summary,
            user:obj.user,
            day:"2015-10-7"
    })

    return loge
}
//刪除數據
const hello3 = async function (obj) {
    let loge = await Log.rizhi.destroy({
           where:{
                id : obj.id
            }   
     })

    return loge
}
查詢數據
const hello4 = async function (obj) {
    let ass = {
        content : obj.content,
        summary : obj.summary,
        user : obj.user, 
    }
    if(!obj.content){
       delete ass.content
    }
    if(!obj.summary){
        delete ass.summary
    }
    if(!obj.user){
        delete ass.user
    }
    let loge = await Log.rizhi.findAll({ 
        
           where:ass   
     })

    return loge
}
//更改數據
const hello5 = async function (obj) {
    let ass = {
        content : obj.content,
        summary : obj.summary,
        user : obj.user, 
    }

    let loge = await Log.rizhi.update(ass,{ 
        
           where:{
                id : obj.id
           }
     })
     let cha = await Log.rizhi.findAll({
        where: {
            id: obj.id,
        }
    })
    return cha
}
需要調用的方法
module.exports = {
    hello,hello1,hello2,hello3,hello4,hello5
}

 最後將表格的內容模塊導入到models.js中

const mysql = require(‘./mysql‘)
//導入數據庫
const Sequelize = require(‘sequelize‘)


//log表內數據格式
var Log = mysql.define(‘log‘, {
    id: {
        primaryKey: true,
        type: Sequelize.INTEGER,
    },
    content: Sequelize.STRING,
    summary: Sequelize.STRING,
    user: Sequelize.STRING,
    day: Sequelize.STRING,
}, {
        freezeTableName: true, // Model 對應的表名將與model名相同
        timestamps: false
});
  
//日誌表內數據格式
var rizhi = mysql.define(‘rizhi‘, {
    id: {
        primaryKey: true,
        type: Sequelize.INTEGER,
    },
    content: Sequelize.STRING,
    summary: Sequelize.STRING,
    user: Sequelize.STRING,
    day: Sequelize.STRING,
}, {
        freezeTableName: true, // Model 對應的表名將與model名相同
        timestamps: false
});

調出兩個表
module.exports = {Log,rizhi}

  這就是一個完整的的node項目了,增刪改查,以後就需要自己去擴展了

讀寫文件的話,就免不了書把txt,excel、sql、之間的數據轉換,以後在講。。。。。。

 

node.js從入門到放棄(一)