Nodejs - 从外部网站获取内容

问题描述 投票:-1回答:1

我写了一个简单的网站,每次重新加载时都会返回一个随机的4位数字。好吧所以我想通过Node.js阅读那个数字。用Google搜索几次,发现axiosfs是我最好的选择..

我的网站:SOLVED

上面的网站在我的浏览器上工作..可能不在你的..所以我为此制作了一个临时网站..它仍然没有按预期工作:SOLVED

我想出了这个:

let axios = require('axios');
let cheerio = require('cheerio');
let fs = require('fs'); 

axios.get('http://thedico.com/third.php')
    .then((response) => {
        if(response.status === 200) {
          const html = response.data;
          const $ = cheerio.load(html); 
            res.send("Status returned 200...!");
    }
    }, (error) => console.log(error) res.send("error...!"));

    res.send("Done...!");

我在Google Cloud Functions a.k.a gCloud中使用此代码,但此代码也不打印输出或返回我的网站数据..我该怎么办?

我确定的事情:

  • 我的网站正常运行,正常速度下加载时间在440MS附近。
  • 我的'gCloud'结算已设置并启用
  • 手动重新加载一切正常

谢谢

node.js google-cloud-functions gcloud
1个回答
1
投票

我试过axios并要求它现在工作正常。你的代码中也有一些错误。

const request = require("request");
const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');

与请求模块

request('https://alexandrarawand.000webhostapp.com/index.php', function (error, response, html) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(html);
        // Get text 
        console.log("------- with request module -------")
        console.log($.text());
        // Get HTML 
        //console.log($.html());
    }
});

使用Axios模块

axios.get('https://alexandrarawand.000webhostapp.com/index.php')
    .then((response) => {
        if (response.status === 200) {
            const html = response.data;
            const $ = cheerio.load(html);
            // Get text 
            console.log("------- with axios module -------")
            console.log($.text());
            // Get HTML 
            //console.log($.html());
        }
    })
    .catch((err) => {
        throw new Error(err);
    });

希望它可以帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.