My urlshortner working in the localhost but its showing "TypeError: Cannot read property 'url' of undefined"

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

Your code so far

const express = require(“express”);
const cors = require(“cors”);
const app = express();
const urlparser = require(“url”);
const dns = require(“dns”);
// Basic Configuration
// bodyparser
const bodyparser = require(“body-parser”);
//connecting database
const mongoose = require(“mongoose”);
mongoose.connect(process.env.db, {
useNewUrlParser: true,
useUnifiedTopology: true
//making schema
const schema = mongoose.Schema({
url: “String”
const Url = mongoose.model(“Url”, schema);

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


app.use("/public", express.static(${process.cwd()}/public));

app.get("/", function (req, res) {
res.sendFile(process.cwd() + “/views/index.html”);
//using bodyparser
app.use(bodyparser.urlencoded({ extended: false }));

// Your first API endpoint"/api/shorturl", (req, res) => {
const bodyurl = req.body.url;
const something = dns.lookup(
(error, address) => {
if (!address) {
res.json({ error: “Invalid URL” });
} else {
const url = new Url({ bodyurl });, data) => {
res.json({ original_url:data.url, short_url: });


console.log(“something”, something);

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

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

Challenge: Request Header Parser Microservice

Link to the challenge: text

Something is trying to read a variable that you think has a var.url property, but the JavaScript interpreter says var is undefined. You try to access several .url properties; start looking there by logging the variable. Post a link to a repl and you’ll probably get better help.

P.S. The links at the bottom of your post are to the header parser.

From what I see, there are three places where .url is used:

  1. const bodyurl = req.body.url;
  2. res.json({ original_url:data.url, short_url: });
  3. res.redirect(data.url);

Case 1 follows body-parser middleware, so I assume it should be fine. Case 3 is guarded by if(!data) so it should be fine also.
What’s left is case 2:, data) => {
 res.json({ original_url:data.url, short_url: });

Looks like saving is erroring, so I’d console.log(err) and see what error I’m getting and then go from there.

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