• NodeJs服务器开发(一)


    用NodeJs没做过大项目,都是自己用来玩耍,记录一下。

    问题:

    怎样写一个最简单的服务器,输出内容到网页上。
    用Vue.js写的前端项目,怎样用NodeJs在本地运行。
    写小项目接口,不想连接MySQL数据库等,但是会有少量数据,还要能做到增删改查,怎么办?
    写小项目接口,连接MySQL数据库怎么做。
    正文
    问题一

    代码

    var http = require("http");
    http.createServer(function(request, response) {
    response.writeHead(200, {
    "Content-Type" : "text/plain;charset=utf-8" // 输出类型
    });
    response.write("你好");// 页面输出
    response.end();
    }).listen(10000); // 监听端口号
    console.log("服务器启动!");
    1
    2
    3
    4
    5
    6
    7
    8
    9
    启动服务

    结果


    问题二
    使用vscode打包vue.js项目会生成dist文件夹,里面会有首页及相关的静态文件。

    代码

    const express = require('express');
    const fs = require('fs');
    const path = require('path');
    const app = express();

    app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    next();
    });

    app.use(express.static(path.resolve(__dirname, 'E:\\Tools\\nodejs\\dist')));

    app.get('/index', function (req, res) {
    const html = fs.readFileSync(path.resolve(__dirname, 'E:\\Tools\\nodejs\\dist\\index.html'), 'utf-8')
    res.send(html)
    })

    app.listen(10001, function () {
    console.log('服务器启动: http://localhost:10001');
    });
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    问题三

    代码

    const fs = require('fs');
    const express = require('express');
    const app = express();

    //设置跨域访问
    app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    next();
    });

    // 获取数据
    function queryMyData() {
    return JSON.parse(fs.readFileSync('./myData.json'));
    }

    // 写入数据
    function writeMyFile(str) {
    var flag = !0;
    fs.writeFile('./myData.json', str, function(err) {
    if (err) {
    flag = !1;
    console.error('----写入失败----');
    } else {
    console.log('----写入成功----');
    }
    });
    return flag;
    }

    // 查询
    app.get('/api/queryData', function(req, res) {
    console.log('访问: /api/queryData');
    res.header("Content-Type", "application/json;charset=utf-8");
    var id = req.query.id || '';
    // 获取数据
    var json = queryMyData();
    var nJson = {user:[], total:0};
    if (id != '') {
    for (var i = 0; i < json.user.length; i++) {
    var u = json.user[i];
    if (u.id == id) {
    nJson.user.push(u);
    }
    }
    } else {
    nJson = json;
    }
    nJson.total = nJson.user.length;
    res.end(JSON.stringify(nJson));
    });

    // 新增
    app.get('/api/addData', function(req, res) {
    console.log('访问: /api/addData');
    res.header("Content-Type", "application/json;charset=utf-8");
    var _id = req.query.id || '';
    var _name = req.query.name || '';
    // 返回内容
    var response = {};
    if (_id == '' || _name == '') {
    response.message = '不能为空';
    } else {
    // 获取数据
    var json = queryMyData();
    // 判断id是否存在
    var a = !0;
    for (var i = 0; a && i < json.user.length; i++) {
    if (json.user[i].id == _id) {
    a = !1;
    break;
    }
    }
    if (!a) {
    response.message = '该ID存在';
    } else {
    json.user.push({id: _id, name: _name});
    json.total = json.user.length;
    var b = writeMyFile(JSON.stringify(json));
    if (b) {
    response.message = '新增成功';
    } else {
    response.message = '新增失败';
    }
    }
    }
    res.end(JSON.stringify(response));
    });

    // 修改
    app.get('/api/editData', function(req, res) {
    console.log('访问: /api/editData');
    res.header("Content-Type", "application/json;charset=utf-8");
    var _id = req.query.id || '';
    var _name = req.query.name || '';
    // 返回内容
    var response = {};
    if (_id == '' || _name == '') {
    response.message = '不能为空';
    } else {
    // 获取数据
    var json = queryMyData();
    // 判断id是否存在
    var a = !0;
    for (var i = 0; a && i < json.user.length; i++) {
    var u = json.user[i];
    if (u.id == _id) {
    u.name = _name;
    a = !1;
    break;
    }
    }
    if (a) {
    response.message = '该ID不存在';
    } else {
    var b = writeMyFile(JSON.stringify(json));
    if (b) {
    response.message = '修改成功';
    } else {
    response.message = '修改失败';
    }
    }
    }
    res.end(JSON.stringify(response));
    });

    // 删除
    app.get('/api/delData', function(req, res) {
    console.log('访问: /api/delData');
    res.header("Content-Type", "application/json;charset=utf-8");
    var _id = req.query.id || '';
    // 返回内容
    var response = {};
    if (_id == '') {
    response.message = 'ID不能为空';
    } else {
    // 获取数据
    var json = queryMyData();
    for (var i = 0;i < json.user.length; i++) {
    if (json.user[i].id == _id) {
    json.user.splice(i, 1);
    break;
    }
    }
    json.total = json.user.length;
    var b = writeMyFile(JSON.stringify(json));
    if (b) {
    response.message = '删除成功';
    } else {
    response.message = '删除失败';
    }
    }
    res.end(JSON.stringify(response));
    });

    app.listen(10002, function() {
    console.log('服务器启动: http://localhost:10002');
    });
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    myData.json
    {“user”:[],“total”:1}

    新增
    http://localhost:10002/api/addData?id=1&name=%E5%BC%A0%E4%B8%89

    查询

    修改
    http://localhost:10002/api/editData?id=1&name=%E7%8E%8B%E4%BA%94

    删除
    http://localhost:10002/api/delData?id=1


    问题四

    代码

    const express = require('express');
    const app = express();
    const mysql = require('mysql');

    app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    next();
    });

    var connection = mysql.createConnection({
    host : '127.0.0.1',
    port : '3306',
    user : 'root',
    password : '123456',
    database : 'my_time'
    });

    connection.connect();

    connection.query('SELECT 1 + 1 AS solution', function(error, results, fields) {
    if (error)
    throw error;
    console.log('数据库连接成功');
    });

    // 时间
    function formatDate() {
    var date = new Date();

    var year = date.getFullYear(), month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate(), hour = date.getHours(), min = date.getMinutes(), sec = date
    .getSeconds();
    var newTime = year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':'
    + sec;
    return newTime;
    }

    //查询统计
    app.get('/api/queryStatistics', function(req, res) {
    res.header("Content-Type", "application/json;charset=utf-8");
    // 查询语句
    var sql = "SELECT COUNT(id) AS 'totalDays', SUM(if_work = '1') AS 'workDays', SUM(work_time) AS 'workTime', SUM(study_time) AS 'studyTime' FROM my_time";

    connection.query(sql, function(error, results, fields) {
    if (error) {
    console.log('查询出错');
    res.end(JSON.stringify({}));
    }

    console.log('\n-------------------------- SELECT ----------------------------');
    console.log(formatDate() + ":" + results);
    res.end(JSON.stringify(results));
    });
    });

    //查询详情
    app.get('/api/queryDetail', function(req, res) {
    res.header("Content-Type", "application/json;charset=utf-8");
    // 获取参数
    var id = req.query.id || '';
    var params = [id];
    // 查询语句
    var sql = " SELECT * FROM my_time where id = ? ";

    connection.query(sql, params, function(error, results, fields) {
    if (error) {
    console.log('查询出错');
    res.end(JSON.stringify({}));
    }

    console.log('\n-------------------------- SELECT ----------------------------');
    console.log(formatDate() + ":" + results);
    res.end(JSON.stringify(results));
    });
    });

    app.listen(10001, function() {
    console.log('服务器启动: http://localhost:10001');
    });
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    结果

  • 相关阅读:
    JPA唯一索引更新删除的问题
    java8时间类的一些封装
    windows 下面必备软件
    YAPI工具在SpringMVC下的使用需要注意的一些问题
    软件
    sublime常用快捷键
    nio学习
    springboot集成rabbitmq的一些坑
    maven子项目的springboot配置
    RabbitMQ 学习
  • 原文地址:https://www.cnblogs.com/onesea/p/15432214.html
Copyright © 2020-2023  润新知