如果我将有效的提取api查询发送到此Express服务器,则工作正常。如果我发送无效查询,则服务器崩溃(ReferenceError:未定义next)。我该如何更改它以便发生错误;
Express server.js:
// Add a new test-resource-a
app.post('/test-resource-a', (request, response) => {
pool.query('INSERT INTO my_table SET ?', request.body, (error, result) => {
if (error) {
next(err);
}
response.status(201).send(`test-resource-a added with id: ${result.insertId}`);
});
});
//An error handling middleware
app.use(function (err, req, res, next) {
res.status(500);
res.send("Oops, something went wrong.")
});
答案 0 :(得分:1)
此错误表示未定义next
方法。
就您而言,我认为您不需要下一种方法。
// Add a new test-resource-a
app.post('/test-resource-a', (request, response) => {
pool.query('INSERT INTO my_table SET ?', request.body, (error, result) => {
if (error) {
response.status(400).send(err);
} else {
response.status(201).send(`test-resource-a added with id: ${result.insertId}`);
}
});
});
//An error handling middleware
app.use(function (err, req, res, next) {
res.status(500);
res.send("Oops, something went wrong.")
});