Node.js-从外部网站获取内容 [英] Nodejs - Get content from external website

查看:117
本文介绍了Node.js-从外部网站获取内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i wrote a simple website that returns a random 4-digit number every time you reload. Okay so i want to read that digit through Node.js.. Googled couple times and found out that axios and fs was my best bet..

我的网站:SOLVED

以上网站可以在我的浏览器上工作..可能无法在您的浏览器上工作..因此我为此创建了一个临时网站..它仍然无法正常运行: SOLVED

The website above works on my browser.. might not on yours.. so i made a temp website for this.. it still doesn't work as expected: 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又称为gCloud一起使用,但是此代码也不打印输出或返回我的网站数据.我该怎么办?

I use this code with Google Cloud Functions a.k.a gCloud but this code nor prints a output or returns my website data.. What should i do?

我确定的事情:

  • 我的网站已启动,并且加载时间大约为440MS正常速度.
  • 我的"gCloud"结算已设置并启用
  • 在手动重新加载时一切正常
  • My website is up and loading time is around 440MS on normal speed.
  • My 'gCloud' billing is set and enabled
  • everything works fine on manual reload

谢谢

推荐答案

我尝试使用axios并请求它现在也可以正常工作.同样,您的代码中也有一些错误.

I tried with axios and request as well it is working fine now. As well you have a couple of bugs in your code.

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

带有请求模块

with Request module

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模块

with Axios module

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);
    });

希望对您有帮助.

这篇关于Node.js-从外部网站获取内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆