I'm building a simple web app that you can post phrases into. It does everything I want, except for showing what someone else appended to the site instantly. I know I could use socket.io for that but I'm wondering if I could achieve the same without using it so I can keep the site as simple as possible. Here's the code
//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]);
}); //this loads saved stuff on the page when you access it
form.onsubmit = (e) => { //this posts input values on server (I omitted var declarations)
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) {//just the function that puts the text on site
const p = document.createElement('p');
const span = document.createElement('span');
p.setAttribute('class', 'p');
container.prepend(p);
p.append(`${data.user} enviou : `)
p.append(span);
span.append(`${data.frasefavorita}`)
p.append(` - ${data.autor}`)
}
//server.js file
mongoose.connect(mongoDB).then(() => console.log('database conectada')).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 => {//this responds to get reqs with mongodb
res.send(JSON.stringify(result))
})
});
app.post('/frases', (req, res) => { //this saves more phrases in mongodb
const frase = new phrase(req.body);
frase.save().then(() => console.log('frase salva'));
});
app.listen(3000, () => {
console.log('listening on 3000')});
CodePudding user response:
I think you are searching for long polling. Here is a good explanation with an example https://javascript.info/long-polling
Here is an comparison of polling, sockets and sse https://codeburst.io/polling-vs-sse-vs-websocket-how-to-choose-the-right-one-1859e4e13bd9
