zoukankan      html  css  js  c++  java
  • node.js从入门到放弃(一)

    以下内容全是我个人理解写出,如有不对,请立刻练习本人进行更改。以免被刚入门的被我带入坑里。

    —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、之间的数据转换,以后在讲。。。。。。

     

  • 相关阅读:
    自我介绍 Self Introduction
    HDU1864 最大报销额
    HDU2955 Robberies
    Sicily 1509. Rails
    Sicily 1031. Campus
    Sicily 1090. Highways
    Sicily 1034. Forest
    Sicily 1800. Sequence
    Sicily 1150. 简单魔板
    CodeVS4919 线段树练习4
  • 原文地址:https://www.cnblogs.com/yishifuping/p/9783917.html
Copyright © 2011-2022 走看看