URL Shortener Microservice | My app works fine but not able to find why I'm getting error in console

Tell us what’s happening:
Describe your issue in detail here.

Your project link(s)

solution: https://sh-url-fcc.herokuapp.com
githubLink: GitHub - AryanKuAg/url-shortener-freecodecamp: Third Project: URL Shortener Microservice to get Backend and apis freecodecamp certificate

image

My code is ----------------------------


require("dotenv").config();

const express = require("express");

const cors = require("cors");

const dns = require("dns");

const app = express();

var bodyParser = require("body-parser");

const Validator = require("validator");

const shortUrl = {

  0: "https://www.google.com",

  1: "https://freeCodeCamp.org",

};

// Basic Configuration

const port = process.env.PORT || 3000;

var urlencodedParser = bodyParser.urlencoded({ extended: false });

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.post("/api/shorturl", urlencodedParser, function (req, res) {

  let formData = req.body.url;

  formData = formData.trim();


  let isCorrect =

    formData.includes("http") &&

    formData.includes(".") &&

    formData.includes("/");


  if (!isCorrect) {

    res.json({ error: "invalid url" });

  } else {

    formData = formData.toLowerCase();

    isThere = false;

    for (let i in shortUrl) {

      if (shortUrl[i] === formData) {

        isThere = true;

      }

    }

    if (!isThere) {

      // url does not exist

      shortUrl[Object.keys(shortUrl).length] = formData;

    }

    myUrl = 0;

    for (let i in shortUrl) {

      if (shortUrl[i] === formData) {

        myUrl = i;

      }

    }

    res.json({ original_url: formData, shortUrl: myUrl });

    // res.redirect("api/shorturl/?formdata=" + formData);

    // console.log("post", req.body.url);

  }

});

app.get("/api/shorturl/:index", (req, res) => {
  let index = req.params.index;
  isMatch = false;
  url = "";
  for (let i in shortUrl) {
    if (index === i) {
      isMatch = true;
      url = shortUrl[i];
    }
  }

  if (isMatch) {

    res.redirect(url);

  } else {

    res.json({ error: "No short URL found for the given input" });

  }

});

app.get("*", (req, res) => {

  res.send("Not Found");

});

app.listen(port, function () {

  console.log(`Listening on port ${port}`);

});

Challenge: URL Shortener Microservice

I’m no expert, but…

You are storing the urls in memory on your server. That will only persist while your server exists and will die if your server shuts down or there is a new instance. I think you want to store that somewhere more permanently, like a DB.