I seem to be having a fundamental problem with the post method. The project is using node.js, mongodb, mongoose, and express. Full code here on glitch.
When I click “POST URL” on my site (which also has the details required for the project) I get the message “Cannot POST /api/shorturl/new”.
I’m not sure where the problem in my code is. I wish I could narrow it down but I’m lost trying to get app.post
to work
var createNewShortUrlDocument = function(url) {
var record = new ShortUrl({original_url: url,
short_url: ShortUrl.length + 1});
console.log(record);
record.save(function (err, record) {
if (err) {
console.log(err);
} else {
console.log("Record Saved");
}
});
};
app.post("api/shorturl/new", function(req, res, next) {
var url = req.body.url;
console.log(url);
var findOriginalUrl = function(originalUrl) {
ShortUrl.findOne({original_url: originalUrl}, function(err, doc) {
if (err) {
console.log(err);
} else {
if (doc !== null) { //if url found send url and short url
res.json({doc});
} else {
createNewShortUrlDocument(originalUrl); //if not found add to database
}
}
})
};
dns.lookup(url, function(err) { //check for valid url
if (err) {
res.json({"error": "invalid URL"});
} else {
findOriginalUrl(url); //check to see if url exists in database
}
})
});