This is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| MongoClient.connect(CONNECTION_STRING, (err, client) => { const db = client.db("issues"); app.post('/api/issues/:project', function (req, res) { const project = req.params.project; const title = req.body.issue_title; const text = req.body.issue_text; const creator = req.body.created_by; if (!(title && text && creator)) { res.status(400).json({err: "missing required field"}); }
const assigned = req.body.assigned_to || ''; const statusText = req.body.status_text || ''; const createdOn = new Date();
db.collection(project).insertOne({ "issue_title": title, "issue_text": text, "created_by": creator, "assigned_to": assigned, "status_text": statusText, "created_on": createdOn, "updated_on": createdOn, "open": true }, {}, (err, doc) => { if (err) { return res.status(500); } else res.json(doc.ops[0]); })
});
|
This is the very interesting error I got:
1
| Uncaught Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
|
This is because the below piece of code has sent the response to user, but the function keeps executing, and attempts to send another request to user.
1 2 3
| if (!(title && text && creator)) { res.status(400).json({err: "missing required field"}); }
|