简体   繁体   English

在 ExpressJS 中显示加载屏幕直到数据准备就绪

[英]Show loading screen until data is ready in ExpressJS

I'm using puppeteer to scrape a job website.我正在使用 puppeteer 来抓取工作网站。 Everything is working so far.到目前为止一切正常。

app.get('/', async (req, res) => {
  res.render('index', {text: 'This is the index page'});  
})

On submit the user gets redirected to an ejs file在提交时,用户被重定向到一个 ejs 文件

<body>
    <div class="container">
        <input type="text" class="submit" id="city-input" placeholder="Submit City">
        <button type="submit" onclick="submitCity()">Submit</button>
    </div>

</body>

script.js脚本.js

function submitCity() {
    const city = document.getElementById('city-input').value;
    const url = 'http://localhost:3000/api/germany/' + city
    window.location.href = url;
    console.log(city);
}

index.js索引.js

app.get('/api/germany/:key', async (req, res) => {
  const city = req.params.key;

  const data = await scraper.scrapeData(city);
  await db.updateDB(data);
  
  await res.render('result', { data: data });
})

So when the user clicks on submit it can take about 1-2 minutes until the result page is ready.因此,当用户点击提交时,可能需要大约 1-2 分钟才能准备好结果页面。 I want to add a loading page/information until the data is scraped and ready to send.我想添加一个加载页面/信息,直到数据被抓取并准备好发送。

You can use fetch to make the request in the background:您可以使用fetch在后台发出请求:

function submitCity() {
    const city = document.getElementById('city-input').value;
    const url = 'http://localhost:3000/api/germany/' + city
    const response = await fetch(url); // make initial request
    const data = await response.json(); // wait for response body, then parse as json
    console.log(data);
}

And on the server, just return the data to the request:在服务器上,只需将数据返回给请求:

app.get('/api/germany/:key', async (req, res) => {
  const city = req.params.key;

  const data = await scraper.scrapeData(city);
  await db.updateDB(data);
  
  return res.json(data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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