node.js - 错误:发送后无法设置标头。在节点 js
问题描述
我是节点 js 的新手,当我尝试从 react 将数据发送到数据库时,在我的节点 js 上出现错误“发送后无法设置标题。我一直在寻找同样的问题,但这并不能帮助我解决这个问题
我试过在帖子上使用 writeHead(第二个),但没有帮助,是因为我发送了相同的图像吗?我只是在发送相同的图像时遇到问题
app.post('/list', function(req, res){
const {namaCabor, descCabor, imgCabor } = req.body;
connectDb.collection('listCabangOlahraga').insertOne(req.body, function(err, res){
console.log(res.insertedCount +'data inserted');
});
res.send(req.body);
});
app.post('/add', function(req, res){
const {categoryName, categoryDesc, categoryImage, namaCabor, descCabor, imgCabor } = req.body;
connectDb.collection('listCategoryCabangOlahraga').insertOne(req.body, function(err, res){
console.log(res.insertedCount +'data inserted');
if(err) throw err;
});
res.writeHead(200, {'Content-Type' : 'application/json'});
res.end(JSON.stringify(req.body));
});
解决方案
快速分析:您的代码涉及写入 MongoDB 集合。它有一个异步回调。我猜 res.write() / res.send() 应该包含在回调中?
如果没有,它们甚至在数据库操作完成之前就被执行,我们不知道它是否成功。
app.post('/list', function(req, res){
const {namaCabor, descCabor, imgCabor } = req.body;
connectDb.collection('listCabangOlahraga').insertOne(req.body, function(err, res){
console.log(res.insertedCount +'data inserted');
// <----- Handle the error here and print response accordingly.
});
res.send(req.body); //Move this inside callback. Return error response if err encountered.
});
app.post('/add', function(req, res){
const {categoryName, categoryDesc, categoryImage, namaCabor, descCabor, imgCabor } = req.body;
connectDb.collection('listCategoryCabangOlahraga').insertOne(req.body, function(err, res){
console.log(res.insertedCount +'data inserted');
if(err) throw err;
// <----- Handle the error here and print response accordingly.
});
res.writeHead(200, {'Content-Type' : 'application/json'}); // Move this inside callback.
res.end(JSON.stringify(req.body)); //Write response from the callback.
});
基本上出现错误是因为 res.write() / res.send() 在设置标题之前被调用
此外,在任一位置重命名 res 对象也是一个好主意(也许可以重命名 MongoDB 写回调中的(结果)对象以避免与快速路由的(响应)对象的res
潜在混淆)res
推荐阅读
- sql - 如何在插入或更新后将数据从 SQL Server 2012 插入到 Postgres,反之亦然?
- scala - 使用 Scala List 操作应用多个业务规则来确定最终结果
- c++ - 通过 dlib 进行人脸识别太慢
- react-native - 在博览会上使用本机反应发起即时电话
- angular - 如何修复“NullInjectorError: No provider for InjectionToken @ngrx/router-store Configuration!” 在我的 Angular 项目上升级到 ngrx v8 之后?
- objective-c - 如何正确地将 WKWebView 添加到 AccessibilityContainer 中的可访问性元素?
- java - 为什么我的意图无法传递数据并接收到 intent.getintExtra 空对象失败?
- postgresql - 如何使用 on 冲突子句更新多行?
- haskell - 如何使用 Haskell 图像处理生成图像
- javascript - jQuery - $(this) + 选择器 - .each()