2

I crawled some contents by JavaScript, and want to print it on HTML.

JavaScript code below is named 'js.js'(worked well on CMD)

var request = require('request');
var cheerio = require('cheerio');
request('...URL...', function (err, res, body) {
    if (err) console.log('Err :' + err);
    var $ = cheerio.load(body);
    $('.class').each(function () {
        var content = $(this).find('.abc').text().trim();
        document.write(content);
    });
});  

But "error:require is not defined" was printed, so I looking for solutions.

I found this page and follow advice which said that use webpack or browseify.

new code(2MB after bundled) give me 2 new error:"fail to fetch" and "access-control-allow-origin". What should I do?

Jayakumar Thangavel
  • 1,884
  • 1
  • 22
  • 29
niceotter
  • 23
  • 4

1 Answers1

0

the require() keyword does not exists in browser/client JavaScript, that is why you need to use webpack to transpile nodejs code to browser compatible javascript.

For the "access-control-allow-origin", the url you are tying to connect to does not allow response to unknown origin.

If you own the API/URL you could add a response header Access-Control-Allow-Origin: *.

For reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

mllduran
  • 86
  • 4
  • Oh..I totally cannot understand cuz study coding for just 2 months.. I will come back after study more. – niceotter Nov 04 '19 at 05:50