I am in the process of creating a straightforward web application where users can input phrases. The app works fine, except for one issue - it doesn't display new additions from other users instantly. I am aware that socket.io could solve this problem, but I am exploring other options to keep the site as minimalistic as possible. Below is the code snippet:
//script.js file
fetch('https://server.jonaso1.repl.co/').then(response => response.json())
.then(data => {
for (let i = 0; i < data.length; i++)
prependPhrase(data[i]);
}); //loads saved content onto the page upon access
form.onsubmit = (e) => { //posts input values to server (variable declarations omitted)
e.preventDefault();
var data = {
[input.name1]:input1.value,
[input2.name]:input2.value,
[input3.name]:input3.value,
};
prependPhrase(data);
fetch('https://server.jonaso1.repl.co/frases', {
method: "POST",
body: JSON.stringify(data),
headers: {"Content-type": "application/json"}
})
};
function prependPhrase(data) {//function to display text on site
const p = document.createElement('p');
const span = document.createElement('span');
p.setAttribute('class', 'p');
container.prepend(p);
p.append(`${data.user} sent : `)
p.append(span);
span.append(`${data.frasefavorita}`)
p.append(` - ${data.autor}`)
}
//server.js file
mongoose.connect(mongoDB).then(() => console.log('database connected')).catch((err) => console.log(err));
app.use(cors());
app.use(express.urlencoded({extended:true}));
app.use(express.json());
app.get('/', (req, res) => {
phrase.find().then(result => {//responds to GET requests with MongoDB data
res.send(JSON.stringify(result))
})
});
app.post('/frases', (req, res) => { //saves additional phrases in MongoDB
const frase = new phrase(req.body);
frase.save().then(() => console.log('phrase saved'));
});
app.listen(3000, () => {
console.log('listening on port 3000')});