Back APIs Route never visited - URL Shortener Microservice

Now the title doesn’t fit anymore (‘Route never visited’).
Is it possible to rename this?

problem now seems is the value of req.params
gets a key (id) with empty value in this route

I do not see such a route in your index.js file.

i have deleted most in my index.js in last minutes (if route not woks i not need anything else. therfore i delete everything first and try find the route with sended data first)
but created a backup to index backup.js

you find it in line 29
in index.js

// https://replit.com/@sl5net/boilerplate-project-urlshortener#index.js
app.get("/api/shorturl/:id", async (req, res) => {

in my backup is ( and was )

index%20(backup).js

// https://replit.com/@sl5net/boilerplate-project-urlshortener#index%20(backup).js
app.get("/api/shorturl/:id", async (req, res) => {

in the new i get now data.
but not from the index(backup).js file.
but route is same. strange for me. hmmm

/‾‾‾ req.params ‾‾‾‾‾‾‾‾‾ 34 
{ id: '3' }
3

Not sure what to tell you. I just checked the index.js file and it works as expected with respect to console.log the id parameter.

1 Like

That means something must have interfered with the proper execution (in the index I’ve been using till today, around 7pm Europe time).

the index that i have used the last 2 days with the same rout gets my
a empty object with same source (at this route).

but in my last index there was/is much stuff into . about 400 lines of code. some side-effect maybe. or i dont know. i need find out or need to programing it completely fresh (maybe not bad idea)

index old (last 2 day or so get my no data) near line 150:

app.get("/api/shorturl/:id", async (req, res) => {
  let id = req.params.id;

index new (today evening) near line 20 that gives me data:

app.post("/api/shorturl/id", async (req, res) => {
  let id = req.body.id;

look pretty same.

from my index.js

// https://replit.com/@sl5net/boilerplate-project-urlshortener#index.js
app.get("/api/shorturl/:id", async (req, res) => {
    console.log(req.params);

but results different:

/‾‾‾ req.params ‾‾‾‾‾‾‾‾‾ line 155 
{ id: 'undefined' }
\___ req.params _________ 

but results different:

/‾‾‾ req.params ‾‾‾‾‾‾‾‾‾ line 34 
{ id: 3 }
\___ req.params _________ 

that was the moment i created many routes to try to get some data from somewhere :smiley:

Btw there was strange behavior today. website was reloading very often. and was not easy to edit (this maybe happens using large files). BTW i closed some clipboard apps at my Desktop like AutoKey-App. Seems helps a bit.

I would start over. You have a ton of code that is not doing anything useful. Have you gone through all the backend challenges for Node and Express. You might benefit from going though them again as it seems from some of the code you have written that you may not quite understand how to create the correct routes.

nut sure if it the best place here.

the result was fetched in line 35 (req.param)

i got a get result, that looks like it was sendet to my scritpt to my script to itself:

npm run start
> shorturl@0.0.3 start
> node index.js
Listening on port 3000  
....
/‾‾‾ req.params object‾‾‾‾‾‾‾‾‾ 35 
{ id: 'dummy' }
\___ req.params _________ 35 
not falid .... EndOf 79 
 not valid = .... 26 

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:393:5)
    at ServerResponse.setHeader (node:_http_outgoing:644:11)
    at ServerResponse.header (/home/runner/boilerplate-project-urlshortener/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/home/runner/boilerplate-project-urlshortener/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/home/runner/boilerplate-project-urlshortener/node_modules/express/lib/response.js:278:15)
    at /home/runner/boilerplate-project-urlshortener/index.js:31:9
    at Layer.handle [as handle_request] (/home/runner/boilerplate-project-urlshortener/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/runner/boilerplate-project-urlshortener/node_modules/express/lib/router/route.js:144:13)
    at Route.dispatch (/home/runner/boilerplate-project-urlshortener/node_modules/express/lib/router/route.js:114:3)
    at Layer.handle [as handle_request] (/home/runner/boilerplate-project-urlshortener/node_modules/express/lib/router/layer.js:95:5)

the index.js

https://replit.com/@sl5net/boilerplate-project-urlshortener#index.js

const express = require('express');
const cors = require('cors');
const app = express();
const dns = require('dns');
const port = process.env.PORT || 3000;

app.use(express.urlencoded({ extended: true })); // Needet for url-encoded parameters parameters. if not used, req.body will be undefined. place it before any other middleware or route handlers.

app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.get('/', function(req, res) {
  res.sendFile(process.cwd() + '/views/index.html');
});

app.post('/api/shorturl', function(req, res) {
  let original_url;
  try {
    // const { url } = req.body; // in the html form name="url" in the in put field
    original_url = req.body.url; // works. is renaming the url
    consoleLogP(original_url, `/api/shorturl original_url`, lNr());
  } catch (error){ 
     consoleLogP(req.body, 'req.body', lNr());
     return;
  }   
  if(!isValidUrl(original_url)){
    consoleLogP(original_url, 'not valid', lNr());  
    res.json({ error: 'invalid url' });
  }

    const JSONresponse = { original_url: 'dummy', short_url: 'dummy' };
    res.json(JSONresponse);  
});

app.get("/api/shorturl/:id", async (req, res) => {
  consoleLogP(req.params, 'req.params', lNr());

/*
that was sendet to myself. confused.
by using 
res.json({ original_url: 'dummy', short_url: 'dummy' }):

/‾‾‾ req.params object‾‾‾‾‾‾‾‾‾ 35 
{ id: 'dummy' }
\___ req.params _________ 35 
*/
  
  return;
});

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

....

I am not sure what you are confused about. What is the exact route you attempted to access tried and what was the result that you are confused about?

in (as is possible to see also above):

app.post('/api/shorturl', function(req, res) {
    console.log(req.params);

the result was:

{ id: 'dummy' }

that confused me (pretty sure that this are not the data that will be sended by the test. confused me also more because my line 30 looks like so:

const JSONresponse = { original_url: 'dummy', short_url: 'dummy' };

BTW sorry for my English i not a native speaker.

Are you talking about a route the tests request or one that you manually tested yourself. If it is one you tested yourself, what is the route, is it a GET or POST route, and how did you attempt to request it?

i not test myself. i mean the tests from
https://www.freecodecamp.org/learn/back-end-development-and-apis/back-end-development-and-apis-projects/url-shortener-microservice

I didn’t know that data from myself might come to my script from another source (apart from my index.html or so).

now it has changed over the night without me doing anything. when I call up the page by clicking on test (first button in the task page),

  1. another message comes up (in the task page)
    Your echo server should repeat words correctly
  2. and the console remains unchanged:

sounds like reported last year in January here: Basic Node and Express - Get Route Parameter Input from the Client - Solution Not Working

I thought you were working on the URL Shortener project.

You would only see this message if you were working on this challenge.

Do you have any advice on how I might fix this? At the moment it only sends this message.

What is the replit you are using and what is the challenge you are working on that gives this message?

it still the same (as from top of this postings) replit boilerplate-project-urlshortener - Replit
The challenge is to short urls and get the short urls back if it will be asked for.

But now… Whey this error is now not there anymore?
i checked it seconds before i pressed the send button… only to be sure.
=> This error not exist anymore. This is strange. :slight_smile: fingerscrossed. I’m feeling a bit like in the movie “Groundhog Day” right now
There seems to be a big time lag. Updates come into effect very late.

https://replit.com/@sl5net/boilerplate-project-urlshortener

I assume you were on the wrong challenge.

I’ve been busy with this task for the past 15 days. Why should I be wrong all of a sudden?

Your remember? we said program everything fresh. i did. its still the same task

I looked at your replit again and I still see all kinds of code you should have deleted. I see tons of console.log statements that are not helping anything. I see you are failing the following test:

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}

You are failing this because if I try to send a post request with a url like:
https://www.freecodecamp.org/news, your app returns:

{"error":"invalid url"}

I should see something like:

{ original_url : 'https://www/freeCodeCamp.org/news', short_url : 'some-unique-id'}

Your isValidUrl function is not working properly.

  return new Promise(resolve => {
    dns.lookup(hostname, error => {
      resolve(!error);
    })
  });

I do not understand why you are returning a Promise here. This function should return either true or false but definitely not a Promise. Currently, I see you returning false in two conditions but never returning true anywhere in the isValidUrl function.

I strongly suggest getting rid of the lnr function and all its references. It is creating a log that is very difficult to read for someone trying to assist you. I am not really interested in helping further until you most of the console.log stuff you currently have in your code.