-1

Very simple HTML pages fetches me the JSON I want with a 200 status code:

<body>
    <button id="login" name="login">login</button>
    <script type="text/javascript">
        document.getElementById('login').onclick = function () {
            fetch('https://api.contonso.com/search/company',
                { method: 'GET' }).then(_ => console.log(_.status));
        };
    </script>
</body>

Which I launch that way :

// index.js
const fs = require('fs');
var http = require('http');


fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function (request, response) {
        response.writeHeader(200, { "Content-Type": "text/html" });
        response.write(html);
        response.end();
    }).listen(8000);
});

So clicking in the HTML pages, fetch works with console.log printing 200 (OK).

Now consider I'm modifying code in index.js with the following one :

// index.js (modified)
const fetch = require('node-fetch');

fetch('https://api.contonso.com/search/company',
    { method: 'GET' }).then(_ => console.log(_.status));

Here console.log prints me 403 (Forbidden)

Could you please explain me what I'm doing wrong? Why it is working in HTML pages and not in JS one?

I'm developing a bot that does not use any frontend, I only need JS files.

Thanks,


In JS only I added the following headers (seen in the browser missing in JS), still the same error

    headers: {
        'Origin': 'https://localhost:8000',
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'en-US,en;q=0.9',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
    }
Arnaud F.
  • 8,252
  • 11
  • 53
  • 102

1 Answers1

-1

The request from the browser is sending some headers like the user agent (that the library is by default setting to node-fetch)

You have to inspect your request response for the reason of the 403, and check the API documentation for further instructions.

moonwave99
  • 21,957
  • 3
  • 43
  • 64
  • Is there a way to see the `headers` sent ? – Arnaud F. May 04 '21 at 11:12
  • In the browser, inspect the Network tab of the devtools. In node-fetch, [see docs](https://github.com/node-fetch/node-fetch#default-headers) – moonwave99 May 04 '21 at 11:22
  • I know this option however the one in the .js file is not captured in the browser because there is no website open (only backend code). – Arnaud F. May 04 '21 at 12:48
  • I know ^^ that's why just the default headers are set. Try to send all the headers sent by the browser for instance, and see if you get the 403 as well! – moonwave99 May 04 '21 at 13:02
  • Updated my initial post, headers added still stuck by CloudFare – Arnaud F. May 04 '21 at 13:10