使用nodejs提取数据并将其返回到浏览器

时间:2019-02-07 13:02:15

标签: javascript node.js

我想通过nodejs获取一些html并在浏览器中获取输出,所以我使用了以下代码

const express = require('express')
const app = express()
const fetch = require("node-fetch");
const port = 3000


app.listen(port, () => console.log(`Example app listening on port ${port}!`));

fetch("https://example.com/results.php")  .then(res => res.text())
  .then(data => obj = data)
  .then(() => 
  app.get('/', (req, res) => res.send(obj))

  )

然后我使用node app

启动了该应用

现在,当我运行localhost:3000时,每次都会给出相同的输出,但是https://example.com/results.php是动态结果页面,每次重新加载时都会返回各种结果。

所以我需要的是每次我打开localhost:3000时,它必须再次获取url并在浏览器窗口中返回新结果,对不起,我对nodejs完全陌生,我只是想从nodejs重新制作php curl。 >

1 个答案:

答案 0 :(得分:5)

您需要将获取登录名放入GET路由中。

从逻辑上进行思考。您想做的是:

  

当用户请求/页面时,获取   “ https://example.com/results.php”并将结果发送给用户。

/路由因此必须始终可用,并且当它被点击时,您将获取所需的资源。它是如何翻译的:

const express = require('express');
const app = express();
const fetch = require("node-fetch");
const port = 3000;


app.get("/", (req, res) => {
    fetch("https://example.com/results.php")
      .then(res => res.text())
      .then((obj) => {
        res.send(obj);
      })
})


app.listen(port, () => console.log(`Example app listening on port ${port}!`));