Skip to content
Advertisement

JS fetch should do action on server write

Given is the following node stack:

  • Client (VUE) (8080)
  • Server (express.js) (3000)

The client sends a get to a server route, inside the server route a task is running that takes some time but could easily been mapped because server is working over an array of data. Is it possible that the server can send a response (write?) which triggers an action on client side?

I’ve tried the following that “works” when checking the network tab in chrome but i don’t know how i can trigger an update on each “write” in my client’s fetch because there just nothing happens till “end” is reached. target would be to show a counter “doing action n of x” that got updated on each write

server.mjs:
...
server.get('/action', async (req, res) => {
    res.setHeader('Content-Type', 'application/json');
// Just to test:
    res.write(JSON.stringify({current: 0, total: 0, status: 'pending'}));
    setTimeout(() => {res.write(JSON.stringify({current: 2, total: 0, status: 'pending'}));},1000);
    setTimeout(() => {res.write(JSON.stringify({current: 3, total: 0, status: 'pending'}));},2000);
    setTimeout(() => {res.write(JSON.stringify({current: 4, total: 0, status: 'pending'}));},3000);
    setTimeout(() => {res.write(JSON.stringify({current: 5, total: 0, status: 'pending'}));},4000);
res.end()
...
client.js (JS part in vue component)
...
const requestOptions = {
          headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": this.authKey,
            "Save-As": this.saveAs,
            "UUID": this.uuid,
            "Name": this.name
          }
        };
fetch(url, requestOptions)
            .then(response => {
              return response.json()
            })
            .then((data) => {
              console.log(data)
              this.downloadLink = data.url
            })
            .catch(error => {
              console.error(error);
              this.showError("Backend not reachable")
            });
      },
...

As i can see “write” is the only solution where it is possible to send updates to the client but how to handle it then?

Advertisement

Answer

i‘ve solved it by using socket.io in my project. thanks for the hint!

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement