URL Shortener Microservice tests not passing

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');
  }
});

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Thanks for that info

Oops I had added <name=“url_input”> because silly me didn’t see the name attribute already declared.

Yes, the test is expecting to send a form field name of url and not url_input. The latter is just the id of the input element.

1 Like

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