Hi there, so I have been trying to solve this problem on my own for a couple of hours, even though everything seems to work just like in the description my code fails all of the tests.
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const mongoose = require('mongoose');
const mongoDB = process.env.DB_URI;
const { Schema } = mongoose;
const bodyParser = require('body-parser');
const dns = require('dns');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const urlSchema = new Schema({
url: String,
id: mongoose.ObjectId,
number: Number
});
const urlModel = mongoose.model("urls", urlSchema);
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.get('/', function(req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
// Your first API endpoint
app.get('/api/hello', function(req, res) {
res.json({ greeting: 'hello API' });
});
app.post('/api/shorturl/new', function(req, res) {
let rand = Math.floor(Math.random() * 10000);
let shortNew = new urlModel({
url: req.body.url,
number: rand
});
const woprotocol = req.body.url;
const regex = /^https?:\/\//i
if(regex.test(woprotocol)) {
const address = woprotocol.replace(regex, '');
dns.lookup(address, { all: true }, function(error, addresses) {
if(error) {
console.error(error);
} else {
let url;
shortNew.save();
res.json({original_url: woprotocol, short_url: rand})
}
});
} else {
res.json({error: "invalid URL"});
}
}
);
app.get('/api/shorturl/:number', function(req, res) {
urlModel.findOne({ number: req.params.number }, function (err, docs) {
if(err) {console.log(err);}
else {
res.redirect(docs.url);
}
});
});
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});
Thanks for any kind of suggestion in advance!