添加数据库一般步骤
- 选择数据库
- 寻找该数据库在npm上已实现的模块,并安装到项目中
- 创建模型,封装数据库访问API
- 把模型添加到Express路由中
选择sqlite3作为数据库
优点:不用下载,适合入门
下载sqlite3
npx yarn add sqlite3
封装数据库访问API
Article.js
const sqlite3 = require('sqlite3').verbose();
const dbname = 'later.sqlite';
const db = new sqlite3.Database(dbname);
db.serialize(()=>{ //如果没有,创建一个'articles表'
const sql = `CREATE TABLE IF NOT EXISTS articles
(id integer primary key,title,content TEXT)`;
db.run(sql)
});
class Article {
static all(cb){
db.all(`SELECT * FROM articles`,cb);
}
static find(id,cb){
db.get(`SELECT * FROM articles WHERE id = ?`,id,cb)
}
static create(data,cb){
const sql = 'INSERT INTO articles(title,content) VALUES (?,?)';
db.run(sql,data.title,data.content,cb);
}
static delete(id,cb){
if(!id){
return cb(new Error('Please provide an id'));
}
db.run('DELETE FROM articles WHERE id = ?',id,cb)
}
}
module.exports = db;
module.exports.Article = Article;
增删改查
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const Article = require('./Article').Article //加载路由模块
const read = require('node-readability');//这个模块提供了一个异步函数,可以下载指定 URL 的页面并将 HTML 转换成简化版。
app.set('port',process.env.PORT || 3000);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/articles',(req,res,next)=>{
Article.all((err,articles)=>{
if(err) return next(err);
res.send(articles);
})
});
app.get('/articles/:id',(req,res,next)=>{
const id = req.params.id;
Article.find(id,(err,article)=>{
if(err) return next(err);
res.send(article)
})
});
app.delete('/articles/:id',(req,res,next)=>{
const id = req.params.id;
Article.delete(id,err=>{
if(err) return next(err)
res.send({message:'Delete'});
})
})
app.post('/articles',(req,res,next)=>{
const url = req.body.url;
read(url,(err,result)=>{
if(err || !result){
res.status(500).send('Error downloading article!');
}else{
Article.create(
{
title:result.title,
content:result.content
},
(err,article)=>{
if(err) return next(err);
res.send('ok')
}
)
}
})
})
app.listen(app.get('port'),()=>{
console.log('App started on port',app.get('port'))
})
实现新增post方法需要下载node-readability插件。
新增文章只需提供一个URL
post localhost:3000/articles
参数: {“url”:“http://manning.com/cantelon2/”}
学习笔记,供自己查阅