URL Shortener Microservice (Error that i cannot figure out )

Hi I am getting an error and it is stumping me. I think its on line 33 in “server.js.” Here is all the things that were contributed in the coding.

                                                                     Server.js
require('dotenv').config();
const express = require('express');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require('cors');
const dns = require('dns');
const urlparser = require('url');
const app = express();

// Basic Configuration
const port = process.env.PORT || 3000;
mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(mongoose.connection.readyState)

const schema = new mongoose.Schema({url: 'string'});
const Url = mongoose.model('Url', schema);

app.use(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.post('/api/shorturl/new', 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((err, 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, (err, data) => {
    if(!data){
      res.json({error: "Invalid URL"})
    }else{
      
    res.redirect(data.url)
    }
  })
})

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


                                                                             .env
PORT=5000
DB_URI="mongodb+srv://user1:<pass>@cluster0.3gehg.mongodb.net/urlshortener?retryWrites=true&w=majority"
 
                                                                                 package.json
{
  "name": "shorturl",
  "version": "0.0.3",
  "description": "API project for freeCodeCamp",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "mongoose": "^5.10.15",
    "mongodb": "^3.6.0"
  },
  "engines": {
    "node": "12.18.3"
  },
  "license": "MIT",
  "devDependencies": {
    "nodemon": "^2.0.4"
  }
}

Tell us what’s happening:

Your code so far

Your browser information:

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

Challenge: URL Shortener Microservice

Link to the challenge:

Hello there,

For future posts, please just provide the link to your project code. Also, I have removed the image with your DB URI, as anyone with access to it can abuse your account/DB.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Can you tell us what the error is?

And I assume that you substitute out “<pass>” in your env file.

You are quite right about the issue. This is a syntax error.

I believe you can figure it out, but here is a hint, if you really are stuck:

In JS, if statements do not use arrow (=>) syntax. You seem to have muddled up an if statement, and an arrow function.

Hope this helps

1 Like

Yes. Sorry about the confusion, but I edited out the password with that.

1 Like

Hi Sky020,

here is the link to my Work. https://glitch.com/edit/#!/frosted-tough-temple?path=server.js%3A4%3A37. I will give you free access to pinpoint the wrong area.

I am still failing, if anyone helps me I will give them full access to my side of the project

I told you what the issue was here: URL Shortener Microservice (Error that i cannot figure out ) - #4 by Sky020

Hi, so I took it out and it is still not letting me pass.

Can you cut and paste that function so we can see what you have now?

And is there any text to the error you are getting?

<p> code </p>

//Code

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

// Basic Configuration
const port = process.env.PORT || 3000;
mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(mongoose.connection.readyState)

const schema = new mongoose.Schema({url: 'string'});
const Url = mongoose.model('Url', schema);

app.use(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.post('/api/shorturl/new', 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((err, 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, (err, data) => {
    if(!data){
      res.json({error: "Invalid URL"})
    }else{
      
    res.redirect(data.url)
    }
  })
})

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

OK, so it’s not so much an error as a failed test…

Can you provide the endpoint so we can see what it is doing?

ADDENDUM: I guess it would be https://frosted-tough-temple.glitch.me

When I use your post field on the home site, it makes a POST to https://frosted-tough-temple.glitch.me/api/shorturl/new and with the data url: https://www.happyhatsforkids.org/, it returns with a 200, {"original_url":"https://www.happyhatsforkids.org/","short_url":"607e1f77d3766f00af52bbaa"}.

So, that seems to work. However … the first failing test says:

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}

But your endpoint works, but you are using the endpoint of api/shorturl/new.

I suspect that if you reexamine what you are calling your endpoints, you might me there.

I don’t know if it is your fault or not - I heard something about these changing recently. I don’t know if that is the case here or not. But if nothing else, you can learn a few valuable lessons here: 1) Always read the specs closely. Triple check. 2) Sometimes they change while you’re building it. Every now and then, they don’t even tell you.

I like double checked everything i did, and once when I got it wrong and looked at some videos to see what i did wrong and that did not help. I am going to lay off of it for a few more days and find another way to plow through it.

Like I said, I think we found it. You have the wrong endpoints defined. You may only need to change those.

hi Kevin, can you pinpoint in my work where to change it. i will give you full access to the account

I think this sums it up. Look at the api endpoint that you are using and what the tests are expecting. They don’t match. There may be other issues, but you won’t know until you get past that.

I was able to monkey with your code and got it to work. I fixed the endpoint. I also fixed the endpoint in index.html, but the test probably doesn’t care about that. I don’t have access to your DB so I had to “fudge” the response for the POST a bit - I just returned the json with the original url and a fixed number. With this, all but the third test past. I can’t get the third test to work because I don’t have access to your DB.

is there a way we can connect via video so you can guide me to the right path? i respect your decision if you decline

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