I am very new to Node; I checked Error: Can't set headers after they are sent to the client but did not understand some terminologies.
Purpose of code: URL shortener post method
I got this error as a result of trying to post a URL that has an undefined DNS address to MongoDB (For example, https://www.iuhwefiudygkufge.com passes the regex test for https but the error below appears)
Schema and Model:
var urlSchema = new mongoose.Schema({
url: String,
shortUrl: String
});
var Url = mongoose.model("Url", urlSchema);
Code for post handler:
app.post("/api/shorturl/new", function(req, res) {
var url = req.body.url;
console.log(url);
var httpRegex = /^(https?:\/\/)/;
if (!httpRegex.test(url)) {
res.json({ error: "invalid url" });
return;
}
if (/^(https:\/\/)/.test(url)) {
var httpsDroppedUrl = url.slice(8);
dns.lookup(httpsDroppedUrl, function(err, address, family) {
console.log("address: %j family: IPv%s", address, family);
if (address == undefined) {
res.json({ error: "invalid url" });
return;
}
});
} else {
var httpDroppedUrl = url.slice(7);
dns.lookup(httpDroppedUrl, function(err, address, family) {
console.log("address: %j family: IPv%s", address, family);
if (address == undefined) {
res.json({ error: "invalid url" });
return;
}
});
}
var newUrl =
(Math.floor(Math.sqrt(url.length)) * 3).toString() +
+Math.floor(Math.random() * 9999).toString() +
Math.floor(Math.random() * 500).toString(); //random method to generate unique identifier
console.log(newUrl);
var data = new Url({
url: url,
shortUrl: newUrl
});
data.save(function(err) {
if (err) {
res.send("Error; please try again");
}
});
res.json(data);
});
Here is the complete error I am getting:
_http_outgoing.js:467
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:467:11)
at ServerResponse.header (/rbd/pnpm-volume/10bcf34e-5673-48ca-b962-5eaef435922b/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/rbd/pnpm-volume/10bcf34e-5673-48ca-b962-5eaef435922b/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/rbd/pnpm-volume/10bcf34e-5673-48ca-b962-5eaef435922b/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/response.js:267:15)
at /app/server.js:58:13
at processTicksAndRejections (internal/process/task_queues.js:83:17)
EDIT 1: next()
replaced with return
I'm not sure where my code is going wrong