Quote API project

https://www.codecademy.com/practice/projects/quote-api

I ran into this problem. whenever I send a GET request on the browser. I received this message.


I do not know why and this is my code.

const express = require('express');
const app = express();

const { quotes } = require('./data');
const { getRandomElement } = require('./utils');

const PORT = process.env.PORT || 3004;

app.use(express.static('public'));

const quotesRouter= express.Router();
app.use('/api/quotes', quotesRouter);

quotesRouter.get('/random',(req,res,next)=>{
    let randomQuote= getRandomElement(quotes);
    if (randomQuote) {
        res.send(randomQuote);
      } else {
        res.status(404).send();
      }
});

app.listen(PORT, ()=>{
    console.log(`Server listening on ${PORT}`);
})

please helping me out! I appreciate with all your help.

1 Like

updated

I can not solve the problem still.

2 Likes

I’ve encountered the exact same issue, and after some testing all i know is that it must be a front-end problem. I’ve tested the helper function and the get request. In the console, the quote appears, but it’s undefined / - undefined on the web page. I’m yet to find a solution unfortunately.

1 Like

Update:

I found the solution, you need to send an object.
Your code: “res.send(randomQuote);”

The solution:
res.send({quote: randomQuote});

And you need to do so with the other requirements as well (get, post, etc);

1 Like

Thank you so much! However, do you know why we have to use

res.send({quote: randomQuote});

why it can be like normal:

res.send(randomQuote);

Again thank you so much for helping me out. I am really appreciate.

Glad i could help you, as for your question, i’m not sure, in the instructions for that exercise it’s clearly states:

" Your API should have a GET /api/quotes/random route. This route should send back a random quote from the quotes data. The response body should have the following shape:

{ quote: {/* quote object */} }"

Honestly i didn’t know what i needed to do at first, but all i know it’s that the body should have that syntax.

But this is just my way of thinking, it might be wrong, but the sripts for displaying the quotes might have something to do with it, because inside the datebase, the functionality works just as intended, but when displaying the quote to the site, that’s when the undefined problem occurs.

Truth is, i don’t fully understand myself, we need a more experienced person to explain.

1 Like