zoukankan      html  css  js  c++  java
  • Node.js Express RESTful 简单例子

    Node.js Express RESTful 一个简单例子,实现对数据的查询和删除基本功能。

    用一个json文件data.json作为读写的数据源

    [
      {
        "id": 1,
        "name": "aa"
      },
      {
        "id": 2,
        "name": "bb"
      }
    ]

    创建 RESTful

    const express = require('express');
    const app = express();
    const fs = require("fs");
     
    app.set('port', process.env.PORT || 3000);
    const jsonFile = __dirname + '/data.json';
     
    //查询所有
    app.get('/list', (req, res) => {
       fs.readFile(jsonFile, 'utf8', (err, data) => {
           console.log(data);
           res.end(data);
       });
    });
     
    //查询单个
    app.get('/detail/:id', (req, res) => { 
       fs.readFile(jsonFile, 'utf8', (err, data) => {
           data = JSON.parse(data);
           const d = data.filter(x => x.id == req.params.id); 
           console.log(d);
           res.end(JSON.stringify(d));
       });
    });
     
     
    const newData = {
        "id": 3,
        "name": "cc"
    };
    //添加
    app.post('/add', (req, res) => { 
       fs.readFile(jsonFile, 'utf8', (err, data) => {
           data = JSON.parse(data);
           data.push(newData);
           console.log(data);
           saveJson(data);
           res.send(data);      
       });
    });
     
    //删除
    app.get('/delete/:id', (req, res) => {
       fs.readFile(jsonFile, 'utf8', (err, data) => {
           data = JSON.parse( data );
           const index = data.findIndex(x => x.id == req.params.id);      
           data.splice(index, 1);       
           console.log(data);
           saveJson(data);
           res.send(data);
       });
    });
     
    //保存到文件
    function saveJson(data){
        fs.writeFile(jsonFile, JSON.stringify(data), "utf-8", err => {
            if (!err) {
                console.log('写入成功!')
            }else{
                console.log('写入失败!')
            }    
        });    
    }
     
    app.listen(app.get('port'), () => {
        console.log('Server listening on: http://localhost:', app.get('port'));   
    });

    Postman测试

    查询所有

    查询单个

    新增

    删除

  • 相关阅读:
    Redis持久化
    Java多线程面试题
    Spring学习总结(1)-注入方式
    SpringCloud常用注解
    Linux安装Redis
    Linux系统安装MySQL
    [转]Java CPU 100% 排查技巧
    ImportError: attempted relative import with no known parent package
    python出现Non-ASCII character 'xe6' in file statistics.py on line 19, but no encoding declared错误
    10个不为人知的 Python 冷知识
  • 原文地址:https://www.cnblogs.com/gdjlc/p/14574478.html
Copyright © 2011-2022 走看看