URL Shortener Microservice

Am I making this more complicated than it is? Been working at this for hours and getting nowhere. This passes 2 out of the 4 tests. Need help passing 2 and 3

const urlStore = {};

app.post('/api/shorturl', (req, res) => {
  const original = req.body.url; 
  

  if (!validUrl.isUri(original)) {
    return res.json({ error: 'invalid url' }); 
  } else {
    const short = shortid.generate(); 
    urlStore[short] = original; 
    res.json({ original_url : original, short_url : short});
  }
});

app.get('/api/shorturl/<short_url>', (req, res) => {
  const short = req.params.short_url; 

  if (urlStore.hasOwnProperty(short)) {
    const original = urlStore[short]; 
    res.redirect(original); 
  } else {
    res.json({error: 'short url not found'}); 
  }
});

This is what I originally had but now I am feeling lost

app.post('/api/shorturl', (req, res) => {
  const original = req.body.url; 
  const short = req.body.shorturl;
  

  if (!validUrl.isUri(original)) {
    return res.json({ error: 'invalid url' }); 
  } else {
    res.json({ original_url : original, short_url : short});
  }
})
  • whats happening here?!
  • are you mkaing use of “any url” or “id”
  • how does “short url” looks like in request body? it seems like you are trying to reference it using a “url” rather than that “generated id” used in previous snippet, right?!

happy coding :slight_smile:

Been adjusting my code all day and nothing is working:/ Feels like I am overcomplicating this

const urlStore = {};

app.post('/api/shorturl', (req, res) => {
  const original = req.body.url; 

  if (!validUrl.isUri(original)) {
    return res.json({ error: 'invalid url' }); 
  } else {
    const short = shortid.generate(); 
    urlStore[short] = original; 
    res.json({ original_url: original, short_url: short });
  }
});

app.get('/api/shorturl/<short_url>', (req, res) => {
  const short = req.params.short_url; 

  if (urlStore.hasOwnProperty(short)) {
    const original = urlStore[short]; 
    res.redirect(original); 
  } else {
    res.json({ error: 'short url not found' }); 
  }
});

Nevermind, got it…this one was hard af :sob: :face_with_spiral_eyes:

const urlStore = {};

app.use(express.urlencoded({ extended: true }));

app.post('/api/shorturl', (req, res) => {
  const original = req.body.url;

  if (!validUrl.isUri(original) || !original.startsWith('http://') && !original.startsWith('https://')) {
    return res.json({ error: 'invalid url' });
  }

  const short = shortid.generate();
  urlStore[short] = original;

  res.json({ original_url: original, short_url: short });
});

app.get('/api/shorturl/:short_url', (req, res) => {
  const short = req.params.short_url;

  if (urlStore.hasOwnProperty(short)) {
    const original = urlStore[short];
    res.redirect(original);
  } else {
    res.json({ error: 'short url not found' });
  }
});

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.