nodeJS第一个例子

首先新建一个文件夹,并在命令行下运行npm init -y

分别修改以下文件

index.js

/*
const express = require('express'); // 加载模块
const app = express();

const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
    res.send('Hello world');
});

app.listen(port, () => {
    console.log('Express web app');
});
*/


/*
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
//const articles = [{title: 'Example'}];
const Article = require('./db').Article;

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

app.use(bodyParser.json()); // 支持编码为json的请求消息体
app.use(bodyParser.urlencoded({extended: true})); // 支持编码为表单的请求消息体

app.get('/articles', (req, res, next) => {
    res.send(articles);
});

app.post('/articles', (req, res, next) => {
    const article = {title: req.body.title};
    articles.push(article);
    res.send(articles);
});

app.get('/articles/:id', (req, res, next) => {
    const id = req.param.id;
    console.log('Fetching:', id);
    res.send(articles[id]);
});

app.delete('/articles/:id', (req, res, next) => {
    const id = req.param.id;
    console.log('Deleting:', id);
    delete articles[id];
    res.send({message: 'Deleted'});
});

app.listen(app.get('port'), () => {
    console.log('App started on port', app.get('port'));
});

module.exports = app;
*/

const read = require('node-readability');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
//const articles = [{title: 'Example'}];
const Article = require('./db').Article;

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

app.use(bodyParser.json()); // 支持编码为json的请求消息体
app.use(bodyParser.urlencoded({extended: true})); // 支持编码为表单的请求消息体


// 
app.use(
    '/css/bootstrap.css',
    express.static('node_modules/bootstrap/dist/css/bootstrap.css')
);

app.get('/articles', (req, res, next) => {
    Article.all((err, articles) => {
        if(err) {
            return next(err);
        }

        // res.send(articles);
        res.format({
            html: () => {
                res.render('article.ejs', {articles: articles});
            },

            json: () => {
                res.send(articles);
            }
        });

    });
});

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');
        }
        Article.create({title: result.title, content: result.content},
            (err, article) => {
             if(err) {
                return next(err);
             }
             res.send('OK');
            }
        );
    });
});

app.get('/articles/:id', (req, res, next) => {
    const id = req.param.id;
    Article.find(id, (err, article) => {
        if(err) {
            return next(err);
        }

        res.send(article);
    });
});

app.delete('/articles/:id', (req, res, next) => {
    const id = req.param.id;
    Article.delete(id, (err) => {
        if(err) {
            return next(err);
        }

        res.send({message: 'Deleted'});
    });
});

app.listen(app.get('port'), () => {
    console.log('App started on port', app.get('port'));
});

module.exports = app;

  

db.js

const sqlite3 = require('sqlite3').verbose();
const dbName = 'later.sqlite';
const db = new sqlite3.Database(dbName); // 连接到一个数据库文件

// 如果没有,创建一个articles表
// 注意下面这个表的表的名字不要写错了,我自己在这边被坑了好长时间
db.serialize(() => {
    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;

  

package.json

{
  "name": "later",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "bootstrap": "^4.3.1",
    "ejs": "^2.6.1",
    "express": "^4.16.4",
    "node-readability": "^3.0.0",
    "sqlite3": "^4.0.6"
  }
}

  

views目录下的head.ejs

<html>
    <head>
        <title>Later</title>
        <link rel="stylesheet" href="/css/bootstrap.css">
    </head>
    
    <body>
        <div class="container">

  

foot.ejs

        </div>
    </body>
</html>

  

article.ejs

<% include head %>

<ul>
    <% articles.forEach((article) => { %>
        <li>
            <a href="/articles/<%= article.id %>">
            <%= article.title %>
            </a>
        </li>
    <% }) %>
</ul>

<% include foot %>

  

运行结果

用postman工具添加文章

 然后在浏览器中输入以下的网址

猜你喜欢

转载自www.cnblogs.com/wylwyl/p/10799602.html