0

So I am trying to get an external website's title using node-fetch in my javascript file in my website and it isn't working here is the code below:

function getTitle(url) {  
  fetch(`${url}`, { 
    mode: 'no-cors'
  }).then((response) => response.text())
    .then((html) => {
      const doc = new DOMParser().parseFromString(html, "text/html");
      const title = doc.querySelectorAll('title')[0];
      return title.innerText;
    });
};

If I run this like doing getTitle('https://google.ca') then it would return with:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'innerText')
    at javascript.js:464:20
(anonymous) @ javascript.js:464
Promise.then (async)
getTitle4 @ javascript.js:461
(anonymous) @ VM1552:1

which I changed the innerText to innerHTMl and .toString() and stuff like that but none worked.

I have also tried different methods like:

function getTitle3(url) {
 $.get(url, function(response) {
var title=(/<title>(.*?)<\/title>/m).exec(response)[1];
alert(title)
});
moie
  • 66
  • 6

1 Answers1

0

are you looking something like this

var http = require("http");

var options = {
    host: "www.google.com",
    port: 80,
    path: "/"
};

var content = "";

var req = http.request(options, function (res) {
    res.setEncoding("utf8");
    res.on("data", function (chunk) {
        content += chunk;
    });

    res.on("end", function () {
        const re = new RegExp('<title>(.*?)<\/title>');
        var title_re = re.exec(content);
        console.log('title=>', title_re[1])
    });
});
bunyaminkirmizi
  • 540
  • 2
  • 6
  • 22
  • If I use the code you sent buny, then I need it in my server file/need browserify or something which is a whole other problem but fetch() works in my javascript file without being defined at all for some reason lol – moie May 16 '22 at 20:27