0

I am going through a Node.JS course on Udemy and as one of the examples for using an API call we are being told to use Superagent and call the Dogs CEO API. I have my code exactly like his in the tutorial and for some odd reason the "data" variable reads the data in the TXT file correctly but when put inside an API in the .get() function for Superagent, the URL doesnt work! I cannot figure out what exactly is wrong here. Please help!

Sorry if the code samples are not rendering correctly on here.

const fs = require('fs')
const superagent = require('superagent')

fs.readFile(`${__dirname}/dog.txt`, 'utf8',(err, data) => {
    console.log(data)
    superagent 
        .get(`https://dog.ceo/api/breed/${data}/images/random`)
        .end((err, res) => {  
            
            console.log(res.body.message)
    })
})

this is what I get in the terminal when I run the file:

[nodemon] clean exit - waiting for changes before restart [nodemon] restarting due to changes... [nodemon] starting node index.js` hound

Breed not found (master breed does not exist) [nodemon] clean exit - waiting for changes before restart `

Why is it reading the data correctly in a console.log but not in the API call?

When I tried running the content outside the get() function I noticed it strangely puts half the URL in a new line like this:

`https://dog.ceo/api/breed/hound

/images/random`

but when I log the URL with "hound" hard-coded it doesn't come out that way, instead it comes out correctly like this: https://dog.ceo/api/breed/hound/images/random

Please help.

I tried hard-coding it or turning the URL into a variable and it causes different errors. I was expecting this to return the proper response of a dog image like in the tutorial.

jfriend00
  • 683,504
  • 96
  • 985
  • 979

1 Answers1

0

I believe that I have reproduced your problem. If your dog.txt ends with a new line (as generally we like to end files) that is being added to the url and confusing it. It should work for you if you either remove the newline from dog.txt, or use ${data.trim()} in your url.

TazHinkle
  • 43
  • 7