【问题标题】:Use nodejs to fetch data and return it to browser使用nodejs获取数据并返回给浏览器
【发布时间】:2019-02-07 13:02:14
【问题描述】:

我想通过 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。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您需要将获取登录名放在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}!`));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多