【问题标题】:Node: Load/read the content of a page from external website(domain)节点:从外部网站(域)加载/读取页面内容
【发布时间】:2019-05-13 08:02:16
【问题描述】:

我的个人网页托管在没有节点的服务器中。

我的服务器端脚本在节点服务器 (Heroku) 上运行。

我正在尝试从我的服务器 js 文件中读取我的个人页面的内容...

这是服务器代码

server.js:

const express = require("express");
const app = express();
const fs = require('fs');
var http = require("http");

const port = process.env.PORT || 3000;
app.use(express.static(__dirname + "/public"));


fs.readFile("http://myportfolio.maxxweb.com", (err, data) => {
    if (err) {
        console.log(err)
    } else {
        console.log("Loaded personal page")
    }
});

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/public/main.html");

});

app.get("/api/names", (req, res) => {
    console.log("names api call... ");
});

app.get('/*', (req, res) => {
    res.redirect('/error.html')

});

app.get("/get-portfolio-page-content", (req, res) => {

    var options = {
        host: 'http://myportfolio.maxxweb.com'
    };

    http.get(options, function(http_res) {
        // initialize the container for our data
        var data = "";

        // this event fires many times, each time collecting another piece of the response
        http_res.on("data", function(chunk) {
            // append this chunk to our growing `data` var
            data += chunk;
        });

        // this event fires *one* time, after all the `data` events/chunks have been gathered
        http_res.on("end", function() {
            // you can use res.send instead of console.log to output via express
            console.log(data);
        });
    });

});

app.listen(port, () => {
    console.log(`Server running at port ` + port);
})

在将代码部署到 Heroku 之前,我从本地运行命令> node server.js。 我收到以下错误:

Server running at port 3000
{ [Error: ENOENT: no such file or directory, open 'C:\maxxpc\project\heroku\http:\myportfolio.maxxweb.com']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'open',
  path:
   'C:\\maxxpc\\project\\heroku\\http:\\myportfolio.maxxweb.com' }

我是 Node 环境的新手。有人请指导我。

【问题讨论】:

  • 必须查看文档。第一点你不会工作:nodejs.org/api/fs.html#fs_url_object_support > 对于大多数 fs 模块函数,路径或文件名参数可以作为 WHATWG URL 对象传递。仅支持使用 file: 协议的 URL 对象。

标签: javascript node.js express


【解决方案1】:

fs 模块用于与文件系统交互,而不是用于发出 HTTP 请求。

您需要使用专门为发出 HTTP 请求而设计的模块,例如 axios 或内置的 http 和 https 模块。

【讨论】:

  • 谢谢。使用 axios.get() 我现在可以在我的 .then() 函数调用中将整个 html 内容作为一大堆垃圾抓取......但是如何理解这些数据呢?我想像这样将这个 DOM 的特定块发送回浏览器。 app.get("/get-portfolio-page-content", (request, response) => { axios.get("").then(data => response.send(block-of-my-DOM)) } );
  • 找到一个用于处理 HTML 的库。
  • 我认为只有当我将内容发送回浏览器时,它才会被识别为正确的 html DOM。或者有没有办法理解 server.js 文件中的 html 标记
  • 您在服务器上使用 HTML 解析器。
猜你喜欢
  • 2011-09-13
  • 2013-02-06
  • 1970-01-01
  • 2018-04-25
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-17
相关资源
最近更新 更多