URL Shortener Microservice challenge

the dns does not work. Why???

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const shortid = require('shortid');
const dns = require('dns');
const { match } = require('assert');
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');
});



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


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

const schemaUrls = new mongoose.Schema({
  original_url: { type: String, required: true },
  short_url: { type: String, required: true }
});
const UrlsIds = mongoose.model('UrlsIds', schemaUrls);

console.log(mongoose.connection.readyState);

// Your first API endpoint
app.post('/api/shorturl/new', function(req, res) {
  let id = shortid.generate();
  let clientReq = req.body.url;

  dns.lookup(clientReq.hostname, (err, address, family) => {
    if(err){
      return res.json({ error: "invalid url" });
    } else {
      let urlsIdsNew = new UrlsIds({
        original_url: clientReq,
        short_url: id
      });

      urlsIdsNew.save((err, data) => {
        if(err){
          console.error(err);
        }
      });
      res.json({ original_url: clientReq, short_url: id });
    }
  });

});

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

What is the specific error you are having? Have you tried adding a console.log(req.body.url) or a console.log(err) in the callback?

when I press post shows me this

image

and should show me error

Okay. The second one is implying that your URL is not getting passed in to your route as you expect, I think. You are going to need to add some console.log() statements in your new URL route to determine what exactly is happening, preferably something like console.log(req.body.url) or even a console.log(req)at the very beginning to see what is being passed to the route on the request.

It seems like "" is a valid host name to the dns module. When I run similar code in a repl I get this warning, but not an error:

The code I used was:

const dns = require('dns')

dns.lookup('', {}, (err, address, family) => {
  console.log('Valid address: %j family: IPv%s', address, family)
})

You’ll have to handle the empty string case yourself before checking with dns.lookup

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