gpt4 book ai didi

javascript - DELETE 在 Express/Postgres 中未按预期工作

转载 作者:行者123 更新时间:2023-12-02 23:27:57 25 4
gpt4 key购买 nike

我使用 JS 创建了一个看板,而没有在 FE 上使用框架。在后端,我使用 Express/Postgres。

我的问题是“删除”操作不起作用。所有其他 CRUD 操作都很好。

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

我的代码如下 -

查询.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 = $1', [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 ($1, $2, $3)',
[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 = $1, plan_id = $2 WHERE id = $3',
[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 = $1',
[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}!`));

我的服务器返回这个:

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 进行同样的操作,我会得到:

“已删除 ID 为 [object Object] 的计划”

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

error message

这是我在前端的 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 上搜索,没有找到类似的情况或解决方案,并且以多种方式更改了我的代码,以至于我失去了踪迹。

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

最佳答案

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

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

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

关于javascript - DELETE 在 Express/Postgres 中未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56649821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com