By saving data from the postman I want to get a response from MongoDB include newly created document
Codes
async save(req, res){
const {score, multiplier, level} = req.body;
const scores = new Result({score, multiplier, level});
const savedRes = await scores.save().then(resp=>{
return resp
.sendStatus(200)
.send({
message:'new record is saved',
data: savedRes
})
}).catch(error=>res.sendStatus(500).send(error))
}
mongo configuration
const app = express()
mongoose.connect(process.env.MONGODB_URL,{
useNewUrlParser: true,
useUnifiedTopology: true,
})
const con= mongoose.connection
try{
con.on('open',() => console.log('db connected'))
} catch(error){
console.log(error)
}
app.use(cors({origin:"*"}))
Actual result
- Document is created in MongoDB Atlas with
internal server error
inpostman
reponse body along with(node:96318) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
in vscode terminal
Expected result
{
message: 'new record is saved',
data: {
level: 1,
multiplier:8
}
}
CodePudding user response:
From the documentation, res.sendStatus(..)
does:
Sets the response HTTP status code to statusCode and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.
So it already sends a response and you try to send a response afterwards through res.send(..)
. You should only set the status through res.status(<statusCode>)
. But since the default status-code is 200
, you can simply do:
const {score, multiplier, level} = req.body;
const scores = new Result({score, multiplier, level});
const savedRes = await scores.save();
res.send({ message:'new record is saved', data: savedRes });
CodePudding user response:
Do not use res.sendStatus
and res.send
at a same time. You can use res.status(200).json({sample : "sample"})
to specify response status code and response body.
async save(req, res){
const {score, multiplier, level} = req.body;
const scores = new Result({score, multiplier, level});
try{
const savedRes = await scores.save();
res.status(200).json({ message:'new record is saved', data: savedRes });
}catch(err){
res.status(500).json({
Message:"Internal Server Error",
Info: err
})
}
}