I have a local server that I have created to learn and practice my backend coding. Right now its in the early stages. My code is just a basic express app, i can require the json file in and i can display it but what im not sure how to do is every time the page is refreshed to load a different question?
app.js
const express = require('express')
const questions = require('./question.json')
const app = express()
const PORT = 3000
app.get('/', (req, res)=>{
res.set('Content-Type', 'text/html');
res.status(200).send("<h1>Hello</h1>");
})
app.listen(PORT, (error) =>{
console.log(`Server is Successfully Running, and App is listening on port ${PORT}`)
})
questions.json
{
"questions":[
{
"1":"Question 1?"
},
{
"2":"Question 2?"
},
{
"3":"Question 3?"
},
{
"4":"Question 4?"
}
]
}
That should work, you might want to define the path of the questions array first instead of having it written out long handed.
const express = require('express')
const questions = require('./questions.json')
const app = express()
const PORT = 3000
app.get('/', (req, res)=>{
JSON.parse(JSON.stringify(questions))
var randomObject = questions.questions[Math.floor(Math.random() * questions.questions.length)]
console.log(randomObject)
res.set('Content-Type', 'text/html');
res.status(200).send("<h1>Hello GFG Learner!</h1>");
})
app.listen(PORT, (error) =>{
console.log(`Server is Successfully Running, and App is listening on port ${PORT}`)
})