nodejs restful服务

nodejs restful服务

        • Express框架
        • SQLite数据库
        • 服务启动
        • 动态设置端口号
        • postman测试

Express框架

帮助我们更简单,快速的搭建node web 框架。

npm install express

创建一个app.js

// express 是一个框架
const express = require('express');
// 消息解析体 用于post请求
const bodyParser = require('body-parser');
// 数据库
const Sqlite = require('./sqlite').Sqlite;

const app = express();

// const url = 'http://www.jsong.wiki:1993/jsong/index.html';
// set PORT = 3001
// mpm start
// 但是没成功
// 但是在bush环境成功了
// cmd也成功了 powershell不行
// const port = process.env.PORT || 3000;

app.set('port', process.env.PORT || 3000);

// json 请求消息体
app.use(bodyParser.json());
// 支持表单请求消息体 x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/restful', (req, res, next) => {
  // res.send('Hello world');
  // res.send(articles);
  Sqlite.all((err, result) => {
    if (err) return next(err);
    res.send(result);
  });
});

app.get('/restful/:id', (req, res, next) => {
  const id = req.params.id;
  console.log('fetching:', id);
  Sqlite.find(id, (err, result) => {
    if (err) return next(err);
    res.send(result);
  });
});

app.delete('/restful/:id', (req, res, next) => {
  const id = req.params.id;
  console.log('delete', id);
  Sqlite.delete(id, err => {
    if (err) return next(err);
    res.send({ message: 'delete' });
  });
});

app.post('/restful', (req, res, next) => {
  const title = req.body.title;
  const content = req.body.content;

  Sqlite.create({ title: title, content: content }, err => {
    if (err) return next(err);
    res.send('OK');
  });
});

// app.listen(port, () => {
//   console.log(`express web app no ${port}`);
// });

app.listen(app.get('port'), () => {
  console.log(`express web app no ${app.get('port')}`);
});


SQLite数据库

SQLite是进程内存数据库,数据会写到一个文件夹里面。入门学习很简单。
如果不需要使用数据,上面的app.js,已经完成了restful的基本需求了。

npm install sqlite3
创建一个sqlite.js

const sqlite3 = require('sqlite3').verbose();
const dbname = 'jsong.sqlite';
const db = new sqlite3.Database(dbname);

db.serialize(() => {
  const sql = `create table if not exists restful 
    (id integer primary key,title,content text)`;
  db.run(sql);
});

class Sqlite {
  static all(callback) {
    db.all(' select * from restful ', callback);
  }

  static find(id, callback) {
    db.get(' select * from restful where id = ? ', id, callback);
  }

  static create(data, callback) {
    const sql = ' insert into restful (title,content) values (?,?) ';
    db.run(sql, data.title, data.content, callback);
  }

  static delete(id, callback) {
    if (!id) return callback(new Error(`do not find ${id}`));
    db.run(' delete from restful where id = ? ', id, callback);
  }
}

module.exports = db;
module.exports.Sqlite = Sqlite;


服务启动

node app.js

动态设置端口号

windows
在cmd窗口按顺序执行
注意:powershell不可以

set port=3001
node app.js

Linux / 或者windows中的 bash窗口

port=3001 node app.js

postman测试

get all
nodejs restful服务_第1张图片
post
nodejs restful服务_第2张图片
get id
nodejs restful服务_第3张图片
delete
nodejs restful服务_第4张图片

你可能感兴趣的:(学习总结,nodejs,express,restful,sqlite)