这是代码:获取错误'ReferenceError:初始化之前无法访问'parsePayload''请帮忙const express = require(\'express\'); const { createToDo,updateToDo } =
这是代码:出现错误, 'ReferenceError: Cannot access 'parsePayload' before initialization'
请帮忙
const express = require("express");
const { createToDo, updateToDo } = require("./types");
const { todo } = require("./db");
const app = express();
app.use(express.json());
app.post('/to-do',async function(req,res){
const createPayload = req.body;
const parsePayload = createToDo.safeParse(parsePayload);
if(!parsePayload.success){
res.status(411).json({
"msg" : "you sent the wrong input"
})
return;
}
await todo.create({
title : createPayload.title,
description : createPayload.description,
completed : false
})
res.json({
"msg" : "To Do Created"
})
})
app.get('/to-do',async function(req,res){
const todos = await todo.find();
console.log(todos);
res.json({
todos
})
})
app.put('/to-do',async function(req,res){
const updatePayload = req.body;
const parsePayload = updateToDo.safeParse(parsePayload);
if(!parsePayload.success){
res.status(411).json({
"msg" : "you send the wrong id or input"
})
return;
}
await todo.update({
_id : req.body.id
},{
completed : true
})
res.json({
"msg" : "todo marked updated"
})
})
app.listen(3000);
parsepaylod 在第 13 行声明,我试图在同一行使用它。仍然出现错误
错误 ReferenceError: Cannot access 'parsePayload' before initializing 发生,因为您尝试在其自己的初始化行中使用 parsePayload。这在 app.post 和 app.put 路由中都会发生。
尝试类似这样的操作
const express = require("express");
const { createToDo, updateToDo } = require("./types");
const { todo } = require("./db");
const app = express();
app.use(express.json());
app.post('/to-do', async function(req, res) {
const createPayload = req.body;
const parseResult = createToDo.safeParse(createPayload); // Corrected line
if (!parseResult.success) {
res.status(411).json({
"msg": "you sent the wrong input"
});
return;
}
const validPayload = parseResult.data;
await todo.create({
title: validPayload.title,
description: validPayload.description,
completed: false
});
res.json({
"msg": "To Do Created"
});
});
app.get('/to-do', async function(req, res) {
const todos = await todo.find();
console.log(todos);
res.json({
todos
});
});
app.put('/to-do', async function(req, res) {
const updatePayload = req.body;
const parseResult = updateToDo.safeParse(updatePayload); // Corrected line
if (!parseResult.success) {
res.status(411).json({
"msg": "you sent the wrong id or input"
});
return;
}
const validPayload = parseResult.data;
await todo.update({
_id: validPayload.id
}, {
completed: true
});
res.json({
"msg": "todo marked updated"
});
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
第 13 行和第 38 行:将 const parsePayload = createToDo.safeParse(parsePayload); 更改为 const parseResult = createToDo.safeParse(createPayload); 以确保将正确的有效负载传递给 safeParse。
使用 parseResult 代替 parsePayload:将变量重命名为 parseResult 以避免混淆。解析后,使用 parseResult.data 访问经过验证的有效负载。
这应该可以解决 ReferenceError 并正确解析输入负载。