Home > Enterprise >  Why do I get a 400 error trying to get data from an html page using fetch API?
Why do I get a 400 error trying to get data from an html page using fetch API?

Time:12-18

Hi I'm doing a coding challenge and I'm trying to fetch data from an html page but I keep getting the 400 error. I don't see where my syntax would be wrong. The Promise returns an empty string as PromiseResult. Why do I not get the data from https://adventofcode.com/2021/day/2/input?

fetch('https://adventofcode.com/2021/day/2/input', {
    method: 'GET',
    mode: 'no-cors', 
    credentials: 'omit',
    headers: {
      'Content-Type': 'text/plain'
    } 
  })
    .then((response) => { 
      response.text();
    })
    .then((html) => {
      var parser = new DOMParser();
        var doc = parser.parseFromString(html, 'text/html');
    })
    .catch((err) => { console.log(err) })

CodePudding user response:

After visting https://adventofcode.com/2021/day/2/input I get information that

Puzzle inputs differ by user.  Please log in to get your puzzle input.

Please check if you are providing your login data correctly.

CodePudding user response:

mode: 'no-cors', 

This says that you are not going to do anything that requires permission to be granted using CORS. Anything that does require CORS will be quietly ignored.

You need CORS permission to read data across origins. Since you have said you aren't going to use CORS, you don't have permission, so you don't get any data.

This is why you get an empty string.


credentials: 'omit',

The input endpoint requires your credentials so that it can give you your input, which is unique to each user. Since told the browser not to send any, the end point doesn't understand the request.


As an aside:

headers: {
  'Content-Type': 'text/plain'
}

This is just nonsense.

It claims that the request includes a body consisting of plain text.

You are making a GET request. There is no body on the request at all.


Advent of code expects you to manually download your input data. It doesn't expect your solution to fetch it from the AoC website.

JS solutions are generally run in Node.js (rather than a web browser) where they can use the fs module to read the local copy of the input file. (Tip: I find it handy to copy/paste the sample data into a sample file to test my results against the worked example on each day).

  • Related