node.js - 收到错误:错误:发送后无法设置标头
问题描述
我正在学习关于 Node.js 的 Wesbos 课程,并创建了一个/add
使用addStore
控制器的 GET 路由:
index.js:
const express = require('express')
const router = express.Router()
const storeController = require('../controllers/storeController')
const { catchErrors } = require('../handlers/errorHandlers')
router.get('/', catchErrors(storeController.getStores))
router.get('/stores', catchErrors(storeController.getStores))
router.get('/add', catchErrors(storeController.addStore))
router.post('/add', catchErrors(storeController.createStore))
router.post('/add/:id', catchErrors(storeController.updateStore))
router.get('/stores/:id/edit', catchErrors(storeController.editStore))
module.exports = router
storeController.js:
exports.addStore = (req, res) => {
res.render('editStore', { title: 'add store'})
}
但是当我去添加路线时,我得到了错误:
错误:发送后无法设置标头。
有什么想法有什么问题吗?
这是 editStore 和 storeform 视图:
编辑商店:
extends layout
include mixins/_storeForm
block content
.inner
h2= title
+storeForm(store)
商店形式:
mixin storeForm(store = {})
form(action=`/add/${store._id || ''}` method="POST" class="card")
label(for="name") Name
input(type="text" name="name" value=store.name)
label(for="description") Description
textarea(name="description")= store.description
- const choices = ['wifi','Open-late','Family Friendly', 'vegetarian','licensced']
- const tags = store.tags || []
ul.tags
each choice in choices
.tag.tag__choice
input(type="checkbox" id=choice value=choice name="tags" checked=(tags.includes(choice)))
label(for=choice) #{choice}
input(type="submit" value="Save" class="button")
捕获错误:
/*
Catch Errors Handler
With async/await, you need some way to catch errors
Instead of using try{} catch(e) {} in each controller, we wrap the function in
catchErrors(), catch any errors they throw, and pass it along to our express middleware with next()
*/
exports.catchErrors = (fn) => {
return function(req, res, next) {
return fn(req, res, next).catch(next);
};
};
/*
Not Found Error Handler
If we hit a route that is not found, we mark it as 404 and pass it along to the next error handler to display
*/
exports.notFound = (req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
};
/*
MongoDB Validation Error Handler
Detect if there are mongodb validation errors that we can nicely show via flash messages
*/
exports.flashValidationErrors = (err, req, res, next) => {
if (!err.errors) return next(err);
// validation errors look like
const errorKeys = Object.keys(err.errors);
errorKeys.forEach(key => req.flash('error', err.errors[key].message));
res.redirect('back');
};
/*
Development Error Handler
In development we show good error messages so if we hit a syntax error or any other previously un-handled error, we can show good info on what happened
*/
exports.developmentErrors = (err, req, res, next) => {
err.stack = err.stack || '';
const errorDetails = {
message: err.message,
status: err.status,
stackHighlighted: err.stack.replace(/[a-z_-\d]+.js:\d+:\d+/gi, '<mark>$&</mark>')
};
res.status(err.status || 500);
res.format({
// Based on the `Accept` http header
'text/html': () => {
res.render('error', errorDetails);
}, // Form Submit, Reload the page
'application/json': () => res.json(errorDetails) // Ajax call, send JSON back
});
};
/*
Production Error Handler
No stacktraces are leaked to user
*/
exports.productionErrors = (err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
};
链接到我的仓库:https ://github.com/GiorgioMartini/learnnode/tree/master/maketogether
解决方案
推荐阅读
- scala - 使用不同的配置文件构建 Scala Play 应用程序
- javascript - 专注于记录交互式网格 oracle apex
- linux - yocto recipe 中的“inherit”关键字和“DEPENDS”关键字用法
- dart - 是否可以在 Dart 中使用条件导入和部分导入?
- python - 有没有办法从网站执行智能搜索?
- c# - OWIN 在 IIS Express 和 IIS 之间产生不同的行为
- angular - Angular 中的问题,输入时带有掩码和验证器
- pascal - 那是什么错误的非法分配以及如何纠正它?
- ios - Cordova 10.0 Ajax 在 iOS 14 中无法运行,但在 Android 中运行良好
- xamarin - Xamarin Forms Splash 未出现在 iOS 14 中