如何删除mysql express.js中选中的行

时间:2018-03-27 14:33:12

标签: mysql node.js express ejs

我试图从数据库中删除选定的行,我已经实现了将数据添加到数据库中。我试图做同样的事情,我在将数据添加到数据库时做了但是看起来像这是行不通的。这就是我所拥有的。

  <div class="container">

  <div class="row">
    <div class="col-md-6 mt-4 text-center">
      <table class="table table-striped">
        <tr>
          <th>ID</th>
          <th>TITLE</th>
          <th>NEWS</th>
          <th></th>
          <th></th>
        </tr>
        <% for(var i = 0; i < news.length; i++) { %>
          <tr>
            <td> <%= news[i].id_news %></td>
            <td> <%= news[i].title %></td>
            <td> <%= news[i].news %></td>
             <td>
               <input type="submit" name="" class="btn btn-link" value="Edit">
             </td>
             <td>
               <input type="submit" name="id_news" class="btn btn-link" value="Delete">
             </td>
            <!--<td><button type="button" name="del" class="close" aria-label="Close" >
                    <span aria-hidden="true">&times;</span>
                </button></td> -->

          </tr>
          <%  } %>
        </table>
      </div>
      <div class="col-md-6 mt-4 card">
        <form action="/news" method="post" class="card-body">
          <h3 class="card-title">Add News</h3>
          <div class="form-group">
            <input id="title" type="text" name="title" class="form-control" placeholder="Title">
          </div>
          <div class="form-group">
            <input type="text" name="news" class="form-control" placeholder="Content">
          </div>
          <input type="submit" class="btn btn-primary">

        </form>
      </div>
    </div>

  </div>

这是程序的另一部分,我尝试使用DELETE FROM表,但它不起作用。

const dbConnection = require('../../config/dbConnection');

module.exports = app => {
const connection = dbConnection();

app.get('/', (req, res) => {
connection.query('SELECT * FROM news', (err, result) => {
  console.log(result);
  res.render('news/news', {
    news: result
    });
  });
});

app.post('/news', (req, res) => {
const { title, news } = req.body;
connection.query('INSERT INTO news SET?', {
  title: title,
  news: news
}, (err, result) => {
  res.redirect('/');
  });
});

app.post('/news', (req, res) => {
const { id_news } =  req.body;
connection.query('DELETE FROM news WHERE id_news = ?', id_news , (err, 
result) => {
  res.redirect('/');
  });
});

}

先谢谢了! :)

1 个答案:

答案 0 :(得分:0)

看起来两条路线都在同一端点上定义:POST /news。 Express只匹配第一个...它怎么知道差异?

您需要使用不同的HTTP方法区分路由:

app.post('/news', (req, res) => { /* create */ })
app.delete('/news', (req, res) => { /* delete */ })

或不同的路径:

app.post('/news', (req, res) => { /* create */ })
app.post('/delete-news', (req, res) => { /* delete */ })

html表单操作需要相应更新。