Back End Development and APIs Projects - URL Shortener Microservice

Can someone tell me what is wrong here, please? I am unable to pass the third test; it says: “When you visit /api/shorturl/short_url>, you will be redirected to the original URL.”

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const {MongoClient} = require('mongodb');

const client = new MongoClient(process.env.DB_URL)
const db = client.db("urlshortener")
const urls = db.collection("urls")
const dns = require('dns')
const urlparser = require('url')

// Basic Configuration
const port = process.env.PORT || 7799;

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({extended: true}))
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.post('/api/shorturl', function(req, res) {
  console.log(req.body)
  const url = req.body.url
  const dnslookup = dns.lookup(urlparser.parse(url).hostname, async (err, address) => {
    if (!address){
      res.json({error: "Invalid url"})
    }else {
      const urlCount = await urls.countDocuments({})
      const urlDoc = ({
        url,
        short_url: urlCount
      })

      const result = await urls.insertOne(urlDoc)
      console.log(result)
      res.json({original_url: url, short_url: urlCount})
    }
  })
});

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

  const { db } = req.app.locals;
const urlDoc = await urls.findOne({ short_url: +shortId })
    .then(doc => {
If (doc === null), return res.send('Uh oh. We could not find a link at that URL');

      res.redirect(urlDoc.url)
    })
    .catch(console.error);
});

app.listen(port, function() {
  console.log(`Listening on port ${port}`);
});

Your project link(s)

solution: boilerplate-project-urlshortener (2) - Replit

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Back End Development and APIs Projects - URL Shortener Microservice

Link to the challenge:

Just to give another hint, you are missing something in the front of the route path that you have in the POST path.

Also, you are not using the correct thing inside the .then() you are mixing await and .then().

Either you use what await returns or you use what you have access to inside the .then(), i.e. urlDoc outside .then() or doc inside .then()

1 Like

I have no idea why it is invalid; the test passes, though.
shorturl instead of short_url works; can you tell why?

app.get('/api/shorturl/:short_url', async (req, res) => {
  const shorturl = req.params.short_url
  const urlDoc = await urls.findOne({ short_url: +shorturl })
  res.redirect(urlDoc.url)
});