Search code examples
node.jsgetrequestnodesaxios

Http vs. www in NodeJS GET Request


I have the following simple GET request using NodeJS:

const axios = require("axios");
axios.get("http://federalregister.gov/api/v1/public-inspection-documents.json")
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

Why does this request work when I am using http://, but not www? For example, the following code works in a browser, but not with axios:

  const axios = require("axios");
    axios.get("www.federalregister.gov/api/v1/public-inspection-documents.json")
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });

Solution

  • http:// - is the protocol. It is mandatory irrespective of whether you try in browser or in Node.js code. In browser, when you enter www.federalregister.gov, browser will automatically prepend "http://" for you. But in code, you will need the url to start with the protocol(http:// or https://), without which the request will fail.

    federalregister.gov and www.federalregister.gov are both domains pointing to the same server. It doesn't matter which one of those you use. As you can see in the nslookup results below both the domains point to the same IP:184.72.241.172.

    > server 8.8.8.8
    DNS request timed out.
        timeout was 2 seconds.
    Default Server:  [8.8.8.8]
    Address:  8.8.8.8
    
    > set type=A
    > federalregister.gov
    Server:  [8.8.8.8]
    Address:  8.8.8.8
    
    Non-authoritative answer:
    Name:    federalregister.gov
    Address:  184.72.241.172
    
    > www.federalregister.gov
    Server:  [8.8.8.8]
    Address:  8.8.8.8
    
    Non-authoritative answer:
    Name:    www.federalregister.gov
    Address:  184.72.241.172