DELETE 在 Express/Postgres 中没有按预期工作

DELETE not working as expected in Express/Postgres

我在FE上用JS做了一个没有框架的看板。在后端,我使用 Express/Postgres.

我的问题是我的 'Delete' 操作不起作用。所有其他 CRUD 操作都很好。

当我使用该应用程序尝试删除 'plan' 时,请求 returns 状态“200”代码,但该条目实际上并未被删除。

我的代码如下-

Queries.js

const Pool = require('pg').Pool;
const pool = new Pool({
 user: 'kanban',
 host: 'localhost',
 database: 'kanbandb',
 password: 'k4nb4n.d3',
 port: 5432
});

const getPlans = (request, response) => {
 pool.query(
  'SELECT * FROM plans ORDER BY project_id ASC',
  (error, results) => {
   if (error) {
    throw error;
   }
   response.status(200).json(results.rows);
  }
 );
};

const getPlanById = (request, response) => {
 const id = parseInt(request.params.id);

 pool.query('SELECT * FROM plans WHERE id = ', [id], (error, results) => {
  if (error) {
   throw error;
  }
  response.status(200).json(results.rows);
 });
};

const createPlan = (request, response) => {
 console.log(request.body);
 const planID = request.body.planID;
 const planName = request.body.planName;
 // const barColor = request.body.barColor;
 const checkbox_state = true;
 pool.query(
  'INSERT INTO plans (plan_id, plan_name, checkbox_state) VALUES (, , )',
  [planID, planName, checkbox_state],
  (error, results) => {
   if (error) {
    throw error;
   }
   console.log(results);
   response.status(201).send(`Plan added with ID: ${results.insertId}`);
  }
 );
};

const updatePlan = (request, response) => {
 //const id = parseInt(request.params.id);
 const { planID, planName, barColor, checkbox_state } = request.body;

 pool.query(
  'UPDATE plans SET plan_name = , plan_id =  WHERE id = ',
  [planID, planName, barColor, checkbox_state],
  (error, results) => {
   if (error) {
    throw error;
   }
   response.status(200).send(`Plan modified with ID: ${id}`);
  }
 );
};

const deletePlan = (request, response) => {
 console.log(request.body);
 const planName = request.body.planName;

 pool.query(
  'DELETE FROM plans WHERE plan_name = ',
  [planName],
  (error, results) => {
   if (error) {
    throw error;
   }
   console.log(results);
   response.status(200).send(`Plan deleted with Name: ${results}`);
  }
 );
};

module.exports = {
 getPlans,
 createPlan,
 updatePlan,
 deletePlan
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

index.js:

const express = require('express');
// const methodOverride = require('method-override');
const https = require('https');
const fs = require('fs');
const bodyParser = require('body-parser');
const app = express();
const db = require('./queries');
const port = 3000;
const cors = require('cors');

// var server = express();
var urlencodedParser = bodyParser.urlencoded({ extended: true });

// override with POST having ?_method=DELETE
// app.use(methodOverride('_method'));
app.use(cors());
app.use(bodyParser.json());
app.use(
 bodyParser.urlencoded({
  extended: true
 })
);

app.options('*', cors()); // include before other routes

app.get('/', (request, response) => {
 response.json({ info: 'Node.js, Express, and Postgres API' });
});

app.get('/plans', db.getPlans);
//app.get("/plans/:id", db.getPlanById);
app.post('/plans', urlencodedParser, db.createPlan);

app.post('/testpost', urlencodedParser, function(req, res) {
 console.log(req.body);
});
app.put('/plans/:id', db.updatePlan);

app.delete('/plans/:planName', urlencodedParser, db.deletePlan);
// console.log(req.body);

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

我的服务器returns这个:

Example app listening on port 3000!{}
Result {
  command: 'DELETE',
  rowCount: 0,
  oid: null,
  rows: [],
  fields: [],
  _parsers: [],
  _types: TypeOverrides {
    _types: {
      getTypeParser: [Function: getTypeParser],
      setTypeParser: [Function: setTypeParser],
      arrayParser: [Object]
    },
    text: {},
    binary: {}
  },
  RowCtor: null,
  rowAsArray: false
} {
  id: '5',
  plan_name: 'hello world',
  plan_id: 'ssss'
}
Result {
  command: 'DELETE',
  rowCount: 0,
  oid: null,
  rows: [],
  fields: [],
  _parsers: [],
  _types: TypeOverrides {
    _types: {
      getTypeParser: [Function: getTypeParser],
      setTypeParser: [Function: setTypeParser],
      arrayParser: [Object]
    },
    text: {},
    binary: {}
  },
  RowCtor: null,
  rowAsArray: false
}

如果我对 Postman 进行同样的尝试,我得到:

'Plan deleted with ID: [object Object]'

在应用程序中完成请求时屏幕上显示的错误在此屏幕截图中。

这是我在前端的 JS 中的内容:

// ************ Delete User ************
function deletePlan(event) {
  event.preventDefault();
  // Pop up a confirmation dialog
  let confirmation = confirm('Are you sure you want to delete this plan?');

  // Check and make sure the user confirmed
  if (confirmation === true) {
    // If they did, do our delete
    $.ajax({
      type: 'DELETE',
      url: 'http://blusrv019.blue.works:3000/plans/' + planName
    }).done(function(response) {
      // Check for a successful (blank) response
      if (response.msg === '') {} else {
        alert('Error: ' + response.msg);
      }
    });
  } else {
    // If they said no to the confirm, do nothing
    return false;
  }
}

// ********* Delete User btn click *********
$('#deletePlanBtn').on('click', deletePlan);

我觉得我错过了一些非常愚蠢的东西,但一直无法弄清楚。

谁能提供一些智慧?我整天都在 WWW 上搜索,但没有找到类似的情况或解决方案,并且以多种方式更改了我的代码,以至于我迷失了方向。

如有任何建议,我们将不胜感激。如果我的 post 不合适或结构不正确(我还是新手),也很抱歉。

您正在寻找 planName 作为 queries.js 文件正文的一部分,但是在您的 index.js 和前端中,您传递的是 planName 作为 URL 参数:

url: 'http://blusrv019.blue.works:3000/plans/' + planName

您应该在 AJAX 请求的正文中提供 planName 或更改 queries.js 文件以使用 request.params.planName.