URL Shortener Microservice - Please help

Ok, then I’d try installing that mongodb-core to see if that helps. However you installed dotenv? Do the same for mongodb-core. If that doesn’t work, I might check any glitch groups and see if anyone has the same problem. I’ve never had this problem so I’m assuming it’s glitch.

Again, I realized that it doesn’t matter if mongo is running locally. You are accessing the mlab db over the internet. I would try that:

npm install --save mongodb-core

@kevinSmith

When I tried installing mongo-db this is the error that I have received

$ pnpm install --save mongodb-core
A store server is running. All store manipulations are delegated to it.
 WARN  using --shamefully-flatten is discouraged, you should declare all of your dependencies in package.json
Packages: +1 -202
+--------------------------------------------------------------------------------------------------------------------------------------------------
 WARN  Cannot find file at /rbd/pnpm-volume/0ab1f909-e174-47e1-b90a-cf2b31d2aa64/node_modules/mongoose although it was listed by readdir
 ERROR  ENOENT: no such file or directory, stat '/rbd/pnpm-volume/0ab1f909-e174-47e1-b90a-cf2b31d2aa64/node_modules/node/bin/node'

My last piece of advice is to simplify, simplify, simplify. Break it down to to the bare bones. What is the minimum things that you can run. Comment out everything but starting the server. Then start adding things in. This is basic debugging. When you isolate it, start logging out variables to see what is amiss.

But it’s time for bed. Sorry.

I am going to give it one more try and it’s bed time for me as well.

I will keep you updated on this thread what happens.

Thank you !

Day # 2 trying to resolve the issue

I have uploaded the whole project on github and then I have uploaded everything on Heroku and the problem occurs when I enter the url, it shows me following error

Not found

I think the issue is that when I click on POST URL, I get only certain link;
https://bocode-short-url.herokuapp.com/api/shorturl/new

My Github is

If anyone can help, I would greatly appreciate.

Again, when you are having difficulty, don’t add more complexity, try to reduce it. Why brink heroku in the mix? Even when I have a working app it usually takes 2-10 tries to get it working on heroku. I would just run it locally. (As I said, it runs fine for me locally.) Do you have node on your computer? Npm? Like I said, you don’t even need Mongo set up since you are using mlab.

I’m guessing you need to learn more about how to set up the environment. Look up youtube videos on setting up a node/express app. Do them. They probably have some for glitch apps. There are tutorial pages. This is not the kind of thing we can step you through step by step in a message board thread.

I know it’s frustrating. It’s very frustrating. I know. But you will get it. If you have specific questions, start a new thread. The more specific the question, the better.

Take baby steps. Just get a “hello world” app. Then add and test. One step at a time so when you test, you know where the problem is.

@kevinSmith

I wanted to try another platform other than glitch.

My curiosity is if it is running locally, why is not running anywhere else ?

Will it running locally be good to pass challenge ?

I don’t know, but it will be good to help you learn and to diagnose what is going wrong. And if you get it working locally, when you set it up on glitch, at least you will know that the code works and can trouble shoot from there. Plus, developing locally is a better experience, for most of us anyway.

@kevinSmith

I already got it working through locally following some instructions that I was able to find hence why I was just curious what I need to do in order to pass the challenge since nothing works for me when I tried uploading it on one of the platforms.

OK, then. I haven’t done the new curriculum so I don’t know what they want. It was heroku when I did it. I would go onto youtube and code along with some people using glitch or find other tutorials. I’m sorry but I can’t advise you on how to use a service I’ve never used. And “how do I use glitch” is too general of a question for the forum anyway.

What I think I am going to do is go through the lessons the FCC has put as new curriculum and see what I am missing.

Thank you @kevinSmith

Cool. Get back to us if you have a question, but usually the more specific the question, the more specific the answer.

And just to reiterate - yes, this is confusing. It certainly too a lot of struggling before it started to come together for me.

I felt bad that I wasn’t able to server you better.

I went and set up a glitch account and tried it out. I was able to get your app to work. Here is the server.js:

'use strict';

var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');

var cors = require('cors');
var bodyParser = require('body-parser');

// var urlHandler = require('./controllers/urlHandler.js');

var app = express();

var mongoURL = process.env.MONGOLAB_URI || 'mongodb://admin:admin1@ds139950.mlab.com:39950/short-url';
console.log('just to confirm, here is my mongoURL  ***' + mongoURL + '***');

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

mongoose.connect(mongoURL);

app.use(cors());
app.use(bodyParser.urlencoded({'extended': false}));

app.use('/public', express.static(process.cwd() + '/public'));

app.get('/', function(req, res){
  res.sendFile(process.cwd() + '/views/index.html');
});

// app.post('/api/shorturl/new', urlHandler.addUrl);
// app.get('/api/shorturl/:shurl', urlHandler.processShortUrl);

app.use(function(req, res, next){
  res.status(404);
  res.type('txt').send('Not found');
});

app.listen(port, function () {
  console.log('Node.js listening ...');
});

(non essential things are commented out)

And here is the package.json:

{
  "name": "shorturl",
  "version": "0.0.1",
  "description": "API project for freeCodeCamp",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^5.0.0-alpha.2",
    "mongodb": "^3.0.8",
    "mongoose": "^5.1.3",
    "cors": "^2.8.4",
    "body-parser": "^1.18.3",
    "node": "^10.3.0"
  },
  "engines": {
    "node": "8.11.2"
  },
  "repository": {
    "type": "git",
    "url": "https://hyperdev.com/#!/project/welcome-project"
  },
  "keywords": [
    "node",
    "hyperdev",
    "express"
  ],
  "license": "MIT"
}

This got the server up and running and rendering the file views/index.html.

If you aren’t getting this, then I’d recommend starting over fresh. If you are getting some other error, please show us exactly what the error is.

1 Like

@kevinSmith

Thank you very much !
This does work ; now the only thing is connecting it on index page so it actually shows everything.

Server is definitely reading

just to confirm, here is my mongoURL  ***mongodb://admin:admin1@ds139950.mlab.com:39950/short-url***

Node.js listening ...

Once again, thank you. I will work on my index page later today.

Ok … I am letting you all know that this project is going to drive me nuts … and I mean N-U-T-S…

No matter which way I try, for some reason it is not connecting server, package and index page … I am so frustrated to the point that I have no idea what to do and I am so … argh ! :rage:

Now that I have got my rant out (still in me but …) I want to let you know what happens.

So I have looked ALL over the place and I can not find any way to connect my database that (thanks to @kevinSmith) is working, nothing and I mean NOTHING is letting me connect it.

This is the tutorial that I have followed from someone that has actually created the database and the database is working for them.

I have no idea why is it not working for me.

Please, help !

The problem is that when I, for example type

https://sour-court.glitch.me/new/https://www.google.com

it is giving me an error

504 Gateway Time-out

Well, in order to help, we’d need to see the code as it stands now.

One thing I do notice is:

app.post('/api/shorturl/new', urlHandler.addUrl)

It’s from the old code. I would expect there to be a parameter in there, something like:

app.post('/api/shorturl/new/:url', urlHandler.addUrl)

Other than that, post the code as it stands. Or you can link to a git.

@kevinSmith

Here is all the code that I have

Server.js

/*******/



'use strict';



var fs = require('fs');

var express = require('express');

var mongodb = require('mongodb');

var shortid = require('shortid');

shortid.characters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$&');

var validUrl = require('valid-url');



var app = express();

var MongoClient = mongodb.MongoClient;



if (!process.env.DISABLE_XORIGIN) {

  app.use(function(req, res, next) {

    var allowedOrigins = ['https://narrow-plane.gomix.me', 'https://www.freecodecamp.com'];

    var origin = req.headers.origin || '*';

    if(!process.env.XORIG_RESTRICT || allowedOrigins.indexOf(origin) > -1){

         console.log(origin);

         res.setHeader('Access-Control-Allow-Origin', origin);

         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    }

    next();

  });

}



app.use('/public', express.static(process.cwd() + '/public'));



app.route('/_api/package.json')

  .get(function(req, res, next) {

    console.log('requested');

    fs.readFile(__dirname + '/package.json', function(err, data) {

      if(err) return next(err);

      res.type('txt').send(data.toString());

    });

  });

  

app.route('/')

    .get(function(req, res) {

		  res.sendFile(process.cwd() + '/views/index.html');

    })



app.route('/new/:url(*)')

    .get( (req,res, next) => {

  //connect to database

  MongoClient.connect(process.env.MONGO_URL, (err, db) => {

        if (err) {

          console.log("Unable to connect to server", err);

        } else {

          //console.log("Connected to server");

          let collection = db.collection('links');

          let url = req.params.url;

          let host = req.get('host') + "/"

          

          //function to generate short link 

          let generateLink = function(db, callback) {

            //check if url is valid

            if (validUrl.isUri(url)){

              collection.findOne({"url": url}, {"short": 1, "_id": 0}, (err, doc) =>{

                if(doc != null){

                  res.json({

                  "original_url": url, 

                  "short_url":host + doc.short

                });

                }

                else{

                   //generate a short code

                    let shortCode = shortid.generate();

                    let newUrl = { url: url, short: shortCode };

                    collection.insert([newUrl]);

                      res.json({

                        "original_url":url, 

                        "short_url":host + shortCode

                      });

                }

              });

            } 

            else {

                console.log('Not a URI');

                res.json({

                  "error": "Invalid url"

                })

            }

          };

          

          generateLink(db, function(){

            db.close();

          });

        }

  }); 

});



//given short url redirect to original url

app.route('/:short')

    .get( (req,res, next) => {

  MongoClient.connect(process.env.MONGO_URL, (err,db) => {

    if (err) {

          console.log("Unable to connect to server", err);

        } else {

          let collection = db.collection('links');

          let short = req.params.short;

          

          //search for original url in db and redirect the browser

          collection.findOne({"short": short}, {"url": 1, "_id": 0}, (err, doc) => {

            if (doc != null) {

              res.redirect(doc.url);

            } else {

              res.json({ error: "Shortlink not found in the database." });

            };

          });

        }

    db.close();

  });

});



// Respond not found to all the wrong routes

app.use(function(req, res, next){

  res.status(404);

  res.type('txt').send('Not found');

});



// Error Middleware

app.use(function(err, req, res, next) {

  if(err) {

    res.status(err.status || 500)

      .type('txt')

      .send(err.message || 'SERVER ERROR');

  }  

})



app.listen(process.env.PORT, function () {

  console.log('Node.js listening ...');

});

Package.json

{
  "name": "fcc-learn-npm-package-json",
  "dependencies": {
    "express": "^4.16.3",
    "mongodb": "^3.0.10",
    "valid-url": "^1.0.9",
    "shortid": "^2.2.8"
  },
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "engines": {
    "node": "4.4.5"
  },
  "repository": {
    "type": "git",
    "url": "https://idontknow/todo.git"
  }
}

.env

MONGO_URL=”mongodb://<dbuser>:<dbpassword>@ds139950.mlab.com:39950/short-url”;

Index.html

<!DOCTYPE html>

<html>



   <head>

      <title>Backend Challenges | Free Code Camp</title>

      <link rel="shortcut icon" href="https://cdn.hyperdev.com/us-east-1%3A52a203ff-088b-420f-81be-45bf559d01b1%2Ffavicon.ico" type="image/x-icon"/>

      <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">

      <link href="/public/style.css" rel="stylesheet" type="text/css">

   </head>



   <body>

      <div class="container">

         <h1>URL Shortener Microservice</h1>

         <h3>Part 4 of Free Code Camp Backend Challenges</h3>

        <h4>

          User stories: </h4>

        <ul>

          <li> I can pass a URL as a parameter and I will receive a shortened URL in the JSON response.</li>

          <li>If I pass an invalid URL that doesn't follow the valid http://www.example.com format, the JSON response will contain an error instead.</li>

          <li> When I visit that shortened URL, it will redirect me to my original link.</li>

        </ul>

        

<h4>

  Example creation usage

        </h4>

https://https://sour-court.glitch.me/new/http://foo.com:80



        <h4>

          Example creation output:

        </h4>

        <pre>

        { 

        "original_url":"http://foo.com:80", 

        "short_url":"https://sour-court.glitch.me/8170" 

        }

        </pre>

        

        <h4>

          Usage:

        </h4>

        https://sour-court.glitch.me/8170

        <h4>

          Will redirect to:

        </h4>

        http://foo.com:80

      </div>

     <footer>

     Coded by BoCode</footer>

   </body>



</html>