简体   繁体   中英

Variable values stays even after reloading

let quote;
let author;

// Get Method For The Root Route
app.get('/', (req, res)=>{
    res.render('home', {
        quote: quote,
        writer: author
    });
});

// Post Method For The Root Route
app.post('/', (req, res)=>{
    // API URL
    const url = 'https://goquotes-api.herokuapp.com/api/v1/random?count=1';

    https.get(url, (response)=>{
        console.log(response.statusCode);

        // On Getting Data From API Parse It And Update Global Variables 
        response.on('data', (data)=>{
            const randomQuote = JSON.parse(data);
            quote = '" ' + randomQuote.quotes[0].text + ' "';
            author = '- ' + randomQuote.quotes[0].author;
            console.log(quote);
            res.redirect('/');
        });
    });
});

I am working with Node and ExpressJS. When I try this web application locally on my computer whenever I reload the page the variables quote and the author becomes undefined (that is what I want), but when I deployed my app on Heroku even after refreshing my page once a value is set to those variables they are remaining same and not becoming empty. I want it to work just like it works on my machine locally, any help would be appreciated

They're defined in global scope, which means that they exist as properties of the global object in node (eg globalThis.quote and globalThis.author), which persists for as long as the application is running.

I assume that when you say that you reload your page locally, you restart your node script/application. However, when you upload your application and reload the page, you don't reload the application only the rendered page, which means that they will still exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM