创建联系人时出错 发送后无法设置标头



当我尝试使用我的应用程序创建联系人时收到以下错误

Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (/home/bas/Desktop/node-backed/node_modules/express/lib/response.js:767:10)
at ServerResponse.json (/home/bas/Desktop/node-backed/node_modules/express/lib/response.js:264:10)
at /home/bas/Desktop/node-backed/routes/route.js:8:18
at /home/bas/Desktop/node-backed/node_modules/mongoose/lib/model.js:4437:16
at process.nextTick (/home/bas/Desktop/node-`    `backed/node_modules/mongoose/lib/helpers/query/completeMany.js:35:39)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)

这是我的应用程序.js代码

var express= require('express'); 
var mongoose= require('mongoose');
var bodyparser=require('body-parser'); 
var cors= require('cors');
var path= require('path');
var app= express();
const route= require('./routes/route');
mongoose.connect('mongodb://localhost:27017/contactlist');
mongoose.connection.on('connected',function(){
console.log('Connected to database mongodb @ 27017'); });
app.use(cors()); app.use(bodyparser.json());
app.use(express.static(path.join(__dirname,'public')));
app.use('/api',route);
app.get('/',function(req,res){
res.send('home'); 
}) 
app.listen(8080, function(req,res){     
console.log('Running'); 
});
/*  https://www.youtube.com/watch?v=wtIvu085uU0 */

这是我的路由器.js代码

const express = require('express'); const router= express.Router();
const Contact = require('../models/contact');
router.get('/contacts', function(req, res, next) {
res.send('Retrieving the contact list')
Contact.find(function(err, contacts) {
res.json(contacts);
}); 
});
router.post('/contact', function(req, res, next) {    
let newContact = new Contact({
first_name:req.body.first_name,
last_name:req.body.last_last,
phone:req.body.phone      
})    
newContact.save(function(err, contacts) {
if(err) {
res.json({ msg: 'Failed to add contact' });
}
else {
res.json({ msg: 'Contact added successfuly' });
}
});
res.send('Post of contacts'); 
});
router.delete('/contacts/:id', function(req, res, next) {    
Contact.remove({ _id: req.params.id }, function(err, result) {
if(err){
res.json(err)
}
else {
res.json(result);
}   
})
});
module.exports=router;

这是我的联系人.js代码

const mongoose= require('mongoose'); const  ContactSchema =
mongoose.Schema({
first_name:{
type:String,
require:true
},
last_name:{
type:String,
require:true
},
phone:{
type:String,
require:true
} });
const Contact = module.exports = mongoose.model('Contact',ContactSchema);

当我访问网址http://localhost:8080/api/contact时,它显示以下错误

events.js:183
throw er; // Unhandled 'error' event
^

错误:发送标头后无法设置标头。

您收到此错误是因为您的GET处理程序向客户端发送响应两次。

router.get('/contacts', function(req, res, next) {
res.send('Retrieving the contact list') // sending response here once
Contact.find(function(err, contacts) {
res.json(contacts); //attempting to send again
}); 
});

您应该只向客户端发送一次响应。

router.get('/contacts', function (req, res, next) {
Contact.find(function (err, contacts) {
if (err) {
return res.json({
msg: err
});
}
res.json({
msg: 'Retrieving the contact list',
contacts: contacts
});
});
});

你应该在定义到节点的路由之前定义你的中间件,所以移动这些行:

app.use(cors()); app.use(bodyparser.json()); 
app.use(express.static(path.join(__dirname,'public')));

在定义应用程序之后,在定义 const route= require('./routes/route'(; 之前,请注意另一件事,最好对查询结果使用 promise,例如保存模型时写入:

newContact.save().then(()=> res.json('success')}).catch((err)=>{..handle error})

或在查找查询中:

Contact.find({your ciritica}).then((contacts)=> res.json(contacts)).catch((err)=>{})

最新更新