Although apparently I’m getting the expected outcomes, the tests for “You can POST a URL to /api/shorturl
and get a JSON response with original_url
and short_url
properties.” and “When you visit /api/shorturl/<short_url>
, you will be redirected to the original URL.” are failing. I don’t understand what’s wrong.
The link for the microservice is https://boilerplate-project-urlshortener.juanrozo89.repl.co and here’s the part of the code that I think is relevant for this issue. If something else is needed I will provide it:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const urlExists = require('url-exists');
const app = express();
const cors = require('cors');
app.post('/api/shorturl', function(req, res) {
const url = req.body.url_input;
urlExists(url, function(err, exists) {
// handle valid url
if(exists) {
const existingUrl = urls.filter(item => item.original_url === url)[0];
// if url was already shoretened and saved
if(existingUrl != null) {
res.json(existingUrl);
}
// if url wasn't shortened and saved before
else {
let short = 0;
urls.map(item => {
if(item.short_url > short) short = item.short_url;
});
short ++;
let newUrlObj = {original_url: url, short_url: short};
urls.push(newUrlObj);
res.json(newUrlObj);
}
}
// handle invalid url
else {
res.json({error: 'invalid url'});
}
});
});
app.get('/api/shorturl/:short', function(req, res) {
const short = req.params.short;
const shortExists = urls.filter(item => item.short_url == short)[0];
if(shortExists != null) {
const originalUrl = shortExists.original_url;
res.redirect(originalUrl);
}
else {
res.status(404).send('URL not found');
}
});