URL Shortener Microservice - How do I get started?

Tell us what’s happening:

I am working on the URL Shortener project on Replit.

How & where do I properly install my MONGO_URI code on Replit?

I use the same MONGO_URI code from my First Cluster I created in MongoDB Atlas.

Do I put the MONGO_URI code in the sample.env file or the Secret Environment Variable or is it both?

When I put in my MONGO_URI key & value in the Secret Environment Variable, it produces a code, const mySecret = process.env['MONGO_URI'] . Where do I put this code on Replit? I do not see the myApp.js file for URL Shortener which I am familiar with.

I also installed the latest versions of mongoose & mongodb on the Replit Console. I type in the console, npm install mongoose & npm install mongodb, which will automatically upload the latest versions on Replit package.json file, within the dependencies array. Did I do this properly?

I want to work on the URL Shortener project, but I do not know if I did the MONGO_URI properly on Replit to get started.

I appreciate any help. :slight_smile:

Your browser information:

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

Challenge: URL Shortener Microservice

Link to the challenge:

If you place your mongo uri in the sample.env file then everyone can see it.
It’s not much of a secret if we know it :wink:

use the secrets tab in replit.

Ok, I put the mongo_uri in the Secrets Environment Variable. I also add in the key and value, which it gives me this code ,const mySecret = process.env['MONGO_URI'] to insert.

As I stated before, where do I insert my mongo_uri code in Replit?

Do I put this code in the server.js file?
If so, then how do I do that?

I understand this URL Shortener require me to put in MONGO_URI, but how do I do it?

I was able to get the first two requirements from freeCodeCamp.

  • Provide your own project, Replit.
  • If you pass an invalid URL that doesn’t follow the valid http://www.example.com format, the JSON response will contain { error: 'invalid url' }

But now I am struggling with these other two test requirements.

  • You can POST a URL to /api/shorturl and get a JSON response with original_url and short_url properties. Here’s an example: { original_url : 'https://freeCodeCamp.org', short_url : 1}

  • When you visit /api/shorturl/<short_url> , you will be redirected to the original URL.


This is the original server.js code structure for URL Shortener in Replit

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();

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

This is what I coded in server.js file

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();

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

//=== I tried to include my MONGO_URI code
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true} );
console.log(mongoose.connect.readyState)
// const mySecret = process.env['MONGO_URI']
//=== ^ Is this how I should put the mongo code in here? 

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. This is where I know I should code here.
app.post('/api/shorturl', function(req, res) {
console.log(req.body);
const bodyurl = req.body.url;

const something = dns.lookup(urlparser.parse(bodyurl).hostname, (error, address) => {
if(!address) {
  res.json({error: "Invalid URL"})
} else {
  const url = new Url({ url: bodyurl })
  url.save((error, data) => {
    res.json({
      original_url: data.url,
      short_url: data.id
    })
  })
}
console.log("dns", error);
console.log("address", address);
})

console.log("something", something);
});

app.get("/api/shorturl/:id", (req, res) => {
  const id = req.params.id;
  Url.findById(id, (error, data) => {
    if(!data){
      res.json({error: "Invalid URL"})
    } else {
      res.redirect(data.url)
    }
  })
})



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

Please let me know where I made my error and how I should fix it.
Thank you

After you have placed the mongo uri in the secrets tab, It doesn’t matter which way you write this because it does the same thing.

This code

mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true} );

is the same as this code

const mySecret = process.env['MONGO_URI']
mongoose.connect(mySecret, {useNewUrlParser: true, useUnifiedTopology: true} );

They are both getting the value of your URI.

The one difference is that this code has the process.env assigned to a variable and then you are using that variable inside the mongoose.connect

const mySecret = process.env['MONGO_URI']
mongoose.connect(mySecret, {useNewUrlParser: true, useUnifiedTopology: true} );

You can choose either way to write it because it does the same thing.
You can just leave your code the way it is.

But you should be getting an error because I don’t see where you have defined mongoose.

Remember that you have to import mongoose into the file and assign it to the mongoose variable if you want to use it.

const mongoose = require('mongoose');

Hope that helps!

Hello. I am working on the URL Shortener project on Replit. I was able to get the first two requirements from freeCodeCamp.

  • Provide your own project, Replit.
  • If you pass an invalid URL that doesn’t follow the valid http://www.example.com format, the JSON response will contain { error: 'invalid url' }

But now I am struggling with these other two test requirements.

  • You can POST a URL to /api/shorturl and get a JSON response with original_url and short_url properties. Here’s an example: { original_url : 'https://freeCodeCamp.org', short_url : 1}

  • When you visit /api/shorturl/<short_url> , you will be redirected to the original URL.


This is the original server.js code structure for URL Shortener in Replit

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();

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

This is what I coded in server.js file

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();

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

//=== I tried to include my MONGO_URI code
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true} );
console.log(mongoose.connect.readyState)
// const mySecret = process.env['MONGO_URI']
//=== ^ Is this how I should put the mongo code in here? 

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. This is where I know I should code here.
app.post('/api/shorturl', function(req, res) {
console.log(req.body);
const bodyurl = req.body.url;

const something = dns.lookup(urlparser.parse(bodyurl).hostname, (error, address) => {
if(!address) {
  res.json({error: "Invalid URL"})
} else {
  const url = new Url({ url: bodyurl })
  url.save((error, data) => {
    res.json({
      original_url: data.url,
      short_url: data.id
    })
  })
}
console.log("dns", error);
console.log("address", address);
})

console.log("something", something);
});

app.get("/api/shorturl/:id", (req, res) => {
  const id = req.params.id;
  Url.findById(id, (error, data) => {
    if(!data){
      res.json({error: "Invalid URL"})
    } else {
      res.redirect(data.url)
    }
  })
})



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

Please let me know where I made my error, what I am missing and how I should fix it.
Thank you :slight_smile:

Hi again!

I haven’t worked on this particular project.

More experience devs will probably be able to help more here.

But I did have a question about this part.

It looks like you are trying to create a document.

But where did you create your model for Url?
Also, where did you create the schema?

Is that in another file?
If so, then you need to import your model into the server.js so you can reference it properly.

I understand, thank you for your response.

Hello there,

You are still missing:

Again:

It would be easier, if you do not mind providing a link to your code (Replit, or GitHub repository, or similar)?

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