更新和删除Express.js中的数据时出现问题

时间:2016-04-15 07:04:22

标签: javascript html sqlite express mustache

我希望能够更新和删除数据库中的评论,出于某种原因,Mustache.render(html, {id:id})会显示正确的ID,但是当我在评论结束时Mustache.render(html, {id:id, person_created:comment, input:comment}) [0]时不会在输入值字段中显示所有必要的数据。对于要更新的​​每条评论,应准备好正确的 person_created 输入

看看下面的代码。

forum.js

var express = require('express');
var sqlite3 = require('sqlite3');
var fs = require('fs');
var Mustache = require ('mustache');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var db = new sqlite3.Database('./forum.db');
var app = express();

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));

app.get('/', function(req, res){
    res.send(fs.readFileSync('./views/topics/index.html', 'utf8'));
});

app.get('/topics', function(req,res) {
    var id = req.params.id;
    res.locals.id = id;
    var template = fs.readFileSync('./views/topics/topics.html', 'utf8');
    db.all("SELECT * FROM topics;", function(err, topics){
        var html = Mustache.render(template, {listoftopics: topics, id:id});
        res.send(html);
    });
});

app.get('/topics/new',  function(req, res){
    res.send(fs.readFileSync('./views/topics/new.html', 'utf8'));
});

app.get('/topics/:id', function(req, res){
    var id = req.params.id;
    res.locals.id = id;

    db.all("SELECT * FROM topics where id= " + id + ";", {}, function(err, topic){
        fs.readFile('./views/topics/edit.html', 'utf8', function(err, html) {
            console.log(topic);
            var renderedHTML = Mustache.render(html, topic[0]);
            res.send(renderedHTML);
        });
    });
});

app.get('/topics/:id/comments/new', function(req, res) {
    var id = req.params.id
    res.locals.id = id
    console.log(res.locals.id)

    var template = fs.readFileSync('./views/comments/newComment.html', 'utf8');

    db.all("SELECT * FROM comments where topic_id= " + id + ";", function(err, comments){
        var html = Mustache.render(template, { id:id})
        res.send(html);
    }); 
});

app.get('/topics/:id/comments', function(req, res){
    var id = req.params.id;
    console.log(id)

    db.all("SELECT * FROM topics WHERE id = " + id + ";", {}, function(err, topics){
        console.log(topics)
        db.all("SELECT * FROM comments WHERE topic_id = " + id + ";", {}, function (err, comments) {
            fs.readFile('./views/topics/show.html', 'utf8', function(err, html){
                var renderedHTML = Mustache.render(html, {body:topics, person_created:comments, input:comments, id:id});
                res.send(renderedHTML);
                console.log(comments);
            });
        });
    });
});

app.get('/topics/:id/comments/edit', function(req, res){
    var id = req.params.id;
    res.locals.id = id

    db.all('SELECT * FROM comments WHERE topic_id = ' + id + ';', {}, function(err, comment){
        fs.readFile('./views/comments/edit.html', 'utf8', function(err, html){
            console.log(comment)
            var renderedHTML = Mustache.render(html, { id:id, person_created:comment, input:comment} );
            res.send(renderedHTML)
        });
    });
});

app.post('/topics/new', function(req, res){
    console.log(req.body);
    db.run("INSERT INTO topics(title, creator, date, body) VALUES ('" + req.body.title + "','" + req.body.creator + "','" + req.body.date + "','" + req.body.body + "')");
    res.redirect("/topics")
});

app.post('/topics/:id/comments/new', function(req, res){
    var id = req.params.id
    res.locals.id = id    

    console.log(id)
    console.log(req.body.topic_id)

    db.run("INSERT INTO comments (person_created, input, topic_id) VALUES ('" + req.body.person_created + "','" + req.body.input + "', '" + id + "')", function(error){             
        if (error) {
            console.log('Error')
        } else {
            console.log('Success')
        }
        console.log(req.body)
    });
    res.redirect("/topics/" + id + "/comments")
});

app.put('/topics/:id', function(req, res){
    var id = req.params.id;
    res.locals.id = id

    var topic = req.body
    console.log(req.body)

    db.run("UPDATE topics SET title =  '" + topic.title + "', creator =  '" + topic.creator + "', date =  '" + topic.date + "', body =  '" + topic.body + "' WHERE id = " + id + ";", function(err, updated){
        if (err) {
            console.log("Error");
        } else {
            console.log('Success')
        }
    });
    res.redirect('/topics')
});

app.put('/topics/:id/comments/edit', function(req, res){
    var id = req.params.id;
    res.locals.id = id
    var comment = req.body

    console.log(req.body)
    db.run("UPDATE comments SET person_created =  '" + comment.person_created + "', input =  '" + comment.input + "' WHERE topic_id = " + id + ";", function(err, updated){
        if (err) {
            console.log("Error");
        } else {
            console.log('Success')
        }
    });

    res.redirect('/topics/' + id + '/comments')
});

app.delete('/topics/:id', function(req, res){
    var id = req.params.id;

    db.run('DELETE FROM topics WHERE id=' + id + ';', function(err, success){
        if (err) {
            console.log("Error")
        }
        else {
            console.log('Success')
        }
    });

    res.redirect('/topics')
});

app.delete('/topics/:id/comments/edit', function(req, res){

    var id = req.params.id;
    var comment = req.body;
    console.log(comment)

    db.run("DELETE FROM comments WHERE person_created=" + comment.person_created + ";", function(err, success) {
        if (err) {
            console.log('Error')
        } else {
            console.log('Success')
        }
    });
    res.redirect('/topics/' + id + '/comments')
});

app.listen(3000, function(){
    console.log("LISTENING!");
});

schema.js

var sqlite3 = require ('sqlite3');
var db = new sqlite3.Database('./forum.db');
db.serialize(function(){
    db.run("CREATE TABLE topics(id integer primary key AUTOINCREMENT, title varchar, creator varchar, date varchar, body varchar);")
    db.run("CREATE TABLE comments(person_created varchar, input varchar, topic_id integer, FOREIGN KEY (topic_id) references topics(id));")
    db.parallelize(function(){
        db.run("INSERT INTO topics(title, creator, date, body) VALUES ('Top R&B Hits of the 80s', 'Michael', '4/15/15', 'Please share some of your favorite R&B Hits from the decade!' );")
        db.run("INSERT INTO comments(person_created, input, topic_id) VALUES ('Sheila', 'Billie Jean by Michael Jackson', 1);")
        db.run("INSERT INTO comments(person_created, input, topic_id) VALUES ('George ', 'Get Outta of My Dreams by Billy Ocean', 1); ")
    })
})

edit.html(评论)

<!DOCTYPE html>
<html lang='en'>
    <head>
        <style type="text/css">
            body{
                background-color: gray;
            }
        </style>
        <meta charset='UTF-8'>
        <title>Create New Comment</title>
    </head>
    <body>
        <form action="/topics/{{id}}/comments/edit?_method=PUT" method="POST">
            <center>
                <label>
                    Name: <br />
                    <input type="text" name="person_created" id='topic_id' rows="10" cols="50" value='{{person_created }}'/>
                </label>
                <br />
                <label>
                    Comment:<br />
                    <textarea type="text" name="input" value='{{ input }}'>
                    </textarea> 
                </label>
                <br />
                <input type="hidden" name="topic_id" value='{{ id }}' />
                <input type='submit' value='UPDATE' />
            </center>
        </form>
        <form action="/topics/{{id}}/comments/edit?_method=DELETE" method="POST">
            <input type='submit' value='DELETE' />
        </form>    
    </body>
</html>

来自edit.html的视图来源的输出(评论)

<!DOCTYPE html>
<html lang='en'>
    <head>
        <style type="text/css">
            body{
                background-color: gray;
            }
        </style>
        <meta charset='UTF-8'>
        <title>Create New Comment</title>
    </head>
    <body>
        <form action="/topics/1/comments/edit?_method=PUT" method="POST">
            <center>
                <label>
                    Name:<br />
                    <input type="text" name="person_created" id='topic_id' rows="10" cols="50" value=''/>
                </label>
                <br />
                <label>
                    Comment:<br />
                    <textarea type="text" name="input" value=''></textarea> 
                </label>
                <br />
                <input type="hidden" name="topic_id" value='1' />
                <input type='submit' value='UPDATE' />
            </center>
        </form>
        <form action="/topics/1/comments/edit?_method=DELETE" method="POST">
            <input type='submit' value='DELETE' />
        </form>
    </body>
</html>

0 个答案:

没有答案