Hello! I can’t figure out why my " When you visit /api/shorturl/<short_url>
, you will be redirected to the original URL." test fails, it seems to work just fine when i’m trying to do everything manually, could somebody help me pls? Code below
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: "false" }));
app.use(bodyParser.json());
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
var urlencodedParser = bodyParser.urlencoded({ extended: false })
const urlSchema = new mongoose.Schema({
originalUrl: {
type: String,
required: true,
},
short: {
type: Number,
//unique: true,
}
})
let urlModel = mongoose.model("urlModel", urlSchema);
app.post('/api/shorturl', (req, res) => {
console.log(req.body)
inputUrl = req.body.url;
let baseshort;
var urlRegex = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(urlRegex);
if (inputUrl.match(regex)) {
urlModel.findOne({originalUrl: inputUrl})
.exec((error,searchresult) => {
console.log(searchresult)
if(!error && searchresult != undefined){
res.json({ original_url : inputUrl, short_url : searchresult.short});
}
if(searchresult == undefined){
urlModel.countDocuments({short: 1},function(err, count){
if(count === 0)
baseshort = 1;
else
baseshort = count+1;
if(!err && count !=undefined){
urlModel.findOneAndUpdate(
{ originalUrl: inputUrl },
{ originalUrl: inputUrl, short: baseshort},
{ new: true, upsert: true },
(error, savedUrl) => {
if (!error) {
res.json({ original_url : inputUrl, short: baseshort});
}
}
)
}
})
}
})
} else {
res.json({ error: 'invalid url' })
}
})
app.get('/api/shorturl/:input', (request, response) => {
let input = request.params.input
urlModel.findOne({short: input}, (error, result) => {
console.log(result)
if(!error && result != undefined){
response.redirect(result.originalUrl)
}else{
response.json('URL not Found')
}
})
})
app.get('/', function(req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});