API not getting random response when I reload

I have this code:

const express = require('express')
const request = require('superagent');
const app = express()
const port = 3000

function txtadvice() {

        .end((err, res) => {
            if (!err && res.status === 200) {
                try {
                } catch (e) {
                    return console.log("An API error occurred")
                const advice = JSON.parse(res.text)
                app.set('view engine', 'ejs'); //Main endpoint, so http://localhost:3000
                app.get('/', function (req, res) {
                    res.render('index', {
                        users: [{
                            name: `"${advice.slip.advice}",` + " Is your advice.."
                        }, ]
            } else {
                console.error(`API call failed: ${err}, status code: ${res.status}`)


app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`)

But whenever I refresh the page, the quote stays the same, what should I do?

Before you answer that, why did you wrap that around a function?

:man_shrugging: didn’t work before, that was the only way I got it to work :confused:


Wait wut, got anything?

I was thinking of just restarting the whole process whenever a user refreshes but thats just weird.

Got anything I can fix it with? @aboutDavid

try…catch functions - interesting
I’m looking at the code ight now

Hey, can you try spinning up a quick script that gets the API text?

Its fine, I just quit on this, lmao.

C’mon man, don’t give up!
I kinda want to know too

Im learning how to use exports now in js.

1 Like

The server app receives the request and responds with the advice thing that was retrieved on app startup.

Refreshing the browser sends another request, it doesn’t restart the server script.

To make a new advice for each request, move the advice code into the handler function of the / request. This will make responses take more time, as it has to wait for the advice to retrieve.

1 Like