Back End Development and APIs Projects - URL Shortener Microservice

Tell us what’s happening:
Hey there,
All of the testing is working on my end for tests #2, #3 and #4.

and none of the tests succeed when i run it through the FCC Test.
I keep getting the following console output:

[TypeError: Failed to fetch]
[TypeError: Failed to fetch]
[TypeError: Failed to fetch]

I am clearly missing something important.
Is there anyone able to point me in the right direction?

Here is the content of index.js :

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const URL = require('url').URL;

const urlRegex = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/

const username = encodeURIComponent("tanguygarnier174");
const password = encodeURIComponent("LMTpF5ge*SbeG6#");
const clusterName = 'urls.cnppn9c.mongodb.net';
const uri = process.env.URI
  .replace('<username>', username)
  .replace('<password>', password)
  .replace('<clusterName>', clusterName)

mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true })

const urlPairSchema = new mongoose.Schema({
  original_url: {
    type: String,
    required: true,
  },
  short_url : {
    type: Number,
  }
})

let Url = mongoose.model('Url', urlPairSchema)

app.post(
  '/api/shorturl',
  bodyParser.urlencoded({extended: false}),
  ({body}, res) => {
    const urlObj = new URL(body.url);
    const urlWithoutProtocol = body.url.replace(`${urlObj.protocol}//`, '');
    
    if( !urlRegex.test(body.url) || urlObj.hostname !== urlWithoutProtocol)
    {
      console.log(`the url is invalid: ${body.url}`)
      return res.json({error: 'invalid url'})
    } 
    else 
    {
      Url.countDocuments()
        .then(count => {
          console.log(`The count is ${count}`)
          const newEntry = { 
            original_url : body.url, 
            short_url : count + 1,
          }
          res.json(newEntry)
          console.log(newEntry)
          Url.create(newEntry).then(data => console.log(data))         
        })
    }
  }
)

app.get(
  '/api/shorturl/:index',
  ({params}, res) => {
    console.log(params)
    Url
      .findOne({short_url: params.index})
      .then(({original_url}) => {
        console.log(new URL(original_url).hostname)
        res.redirect(301, original_url)
      })
  }
)

// 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}`);});

Your project link(s)

solution: boilerplate-project-urlshortener - 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:

You are not validating the URL correctly. Use the suggested Node dns method or an npm package for the validation.

Do not put your DB username and password in the code. Use the env file (Replit Secrets). I would suggest you change your credentials.

Thanks a lot for considering my issue.
I’ve been looking into dns.lookup method.
Using info from this other post,
I have updated my code to the following:

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const URL = require('url').URL;
**const dns = require('dns')**

**const username = encodeURIComponent(process.env.username);**
**const password = encodeURIComponent(process.env.password);**
const clusterName = 'urls.cnppn9c.mongodb.net';
const uri = process.env.URI
  .replace('<username>', username)
  .replace('<password>', password)
  .replace('<clusterName>', clusterName)

mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true })

const urlPairSchema = new mongoose.Schema({
  original_url: {
    type: String,
    required: true,
  },
  short_url : {
    type: Number,
  }
})

let Url = mongoose.model('Url', urlPairSchema)

app.post(
  '/api/shorturl',
  bodyParser.urlencoded({extended: false}),
  ({body}, res) => {
    const urlObj = new URL(body.url);
    
    **dns.lookup(**
**      urlObj.hostname,**
**      (err, address, family) => {**
**        if(err){ res.json({ error: 'invalid url' })}**
**        else {**
**          Url**
**            .countDocuments()**
**            .then(count => {**
**              console.log(`The count is ${count}`)**
**              const newEntry = { **
**                original_url : body.url, **
**                short_url : count + 1,**
**              }**
**              console.log(newEntry)**
**              Url.create(newEntry).then(data => console.log(data))**
**              res.json(newEntry)**
**            })**
**        }**
**      }**
**    )**
  }
)

app.get(
  '/api/shorturl/:index',
  ({params}, res) => {
    console.log(params)
    Url
      .findOne({short_url: params.index})
      .then(({original_url}) => {
        console.log(new URL(original_url).hostname)
        res.redirect(301, original_url)
      })
  }
)

// 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}`);});

Although my code is better than it was, the issue remains the same with the FCC tests console outputs still displaying:

[TypeError: Failed to fetch]
[TypeError: Failed to fetch]
[TypeError: Failed to fetch]

I fail to understand which kind of issue would affect the success of both tests #3 and #4.
Again, things seem to be working fine when doing my own testing.

Problem solved !!

i forgot to place the

app.use(cors());

before

app.post(...
app.get(...

Thanks for taking the time.

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