我正在尝试使用 Node、Express 和 sqlite3 创建一个简单的待办事项应用程序。我有一个完美运行的 GET 和 POST 方法,但是我的 PUT 和 DELETE 没有被访问,相反我遇到了 404 状态和
CANNOT DELETE/PUT \todos
.
我没有为请求使用任何 html 表单,一切都在后端完成,我使用 Thunder 执行请求。
我有一个创建数据库的
database.js
,这是具有所有端点的app.js
:
const express = require('express');
const bodyParser = require('body-parser');
const db = require('./database.js');
let port = 3000 || 5000;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : true}));
app.get('/', (req, res) => {
res.json({Page: 'Main page'});
});
app.get('/todos', (req, res) => {
db.all(`SELECT * FROM todo`, (err, rows) => {
if(err) return res.status(500).json({err: err.message});
res.json(rows);
});
});
app.post('/todos', (req, res) => {
const {task} = req.body;
console.log(req.body);
if(!task) return res.status(400).json({error: 'Task not specified.'});
db.run(`INSERT INTO todo (task) VALUES (?)`, [task], function(err){
if(err) return res.status(500).json({err: err.message});
res.json({id: this.lastID, task: task, completed: false});
});
});
app.put('/todos/:id', function(req, res) {
const {id} = req.params;
db.run(`UPDATE todo SET completed = 1 WHERE id = ?`, [id], function(err){
if(err) return res.status(500).json({err: err.message});
console.log(id);
if(this.changes === 0) return res.status(404).json({err: 'Task not found.'});
res.json({ message: 'Todo marked as completed.'});
});
});
app.delete('/todos/:id', function(req, res){
const {id} = req.params;
console.log(id);
db.run(`DELETE FROM todo WHERE id = ?`, [id], function(err){
if(err) return res.status(500).json({err: err.message});
console.log(id);
if(this.changes === 0) return res.status(404).json({err: 'Task not found.'});
res.json({ message: 'Todo successfully deleted.'});
});
});
app.listen(port, () => {
console.log(`Listening on the port ${port}`);
});`
我在 VSCode 上使用 Thunder 发出请求,这是 PUT 和 DELETE 方法的响应,状态为
404 Not Found
.
要求:
DELETE
: http://localhost:3000/todos/?id=2
PUT
: http://localhost:3000/todos/?id=2
以及示例响应:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot DELETE /todos</pre>
</body>
</html>
有人知道如何解决这个问题吗?提前谢谢你。
要匹配
'/todos/:id'
的路线,您应该使用 http://localhost:3000/todos/2
而不是 http://localhost:3000/todos/?id=2
.
使用
http://localhost:3000/todos/?id=2
你将从查询字符串中获取 id。 (加上它与提供的路线签名不匹配。)