Tell us what’s happening:
I have completed the challange based on a youtube walkthrough, after failing some time with other solutions and their documentations. This solution seems to give back all the proper responses, however FCC doesn’t seem to accept the JSON response for invalid URLs.
I tried to modify the text of the error message, but it seems there is another problem. Could anyone recommend something how to solve this?
Here is my server.js:
Your code so far
'use strict';
require('dotenv').config();
const express = require('express');
const mongo = require('mongodb');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
// 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.listen(port, function() {
console.log(`Listening on port ${port}`);
});
// connect to mongoDB
const uri = process.env.MONGO_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000
});
const connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error: '));
connection.once('open', () => {
console.log("MongoDB connection successful.");
});
//define url schema and model
let urlSchema = new mongoose.Schema({
original_url: {type: String, required: true},
short_url: Number
});
let urlModel = new mongoose.model('URL', urlSchema);
// Get the input URL
let responseObj = {};
app.post('/api/shorturl/new', bodyParser.urlencoded({ extended: false }), (req, res) => {
let inputUrl = req.body.url;
//check validity of URL
let urlRegex = new RegExp(/[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi);
if(!inputUrl.match(urlRegex)) {
res.json({error: 'Invalid URL'});
return
}
responseObj['original_url'] = inputUrl;
let inputShort = 1;
urlModel.findOne({}).sort({short_url: 'desc'}).exec((err, result) => {
if(!err && res != undefined) {
inputShort = result.short_url + 1;
}
if(!err) {
urlModel.findOneAndUpdate(
{original_url: inputUrl},
{original_url: inputUrl, short_url: inputShort},
{new: true, upsert: true},
(err, savedUrl) => {
if(!err) {
responseObj['short_url'] = savedUrl.short_url;
res.json(responseObj);
}
}
);
}
});
//res.json(responseObj);
});
app.get('/api/shorturl/:input', (req, res) => {
let input = req.params.input;
urlModel.findOne({short_url: input}, (err, result) => {
if(!err && result != undefined) {
res.redirect(result.original_url)
} else {
res.json('URL not found')
}
});
});
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36
.
Challenge: URL Shortener Microservice
Link to the challenge: