freeCodeCamp / demo-projects

Example certification projects for our programming curriculum
https://www.freecodecamp.org/learn
BSD 3-Clause "New" or "Revised" License
142 stars 89 forks source link

fix: simplify protocol handling #599

Closed scissorsneedfoodtoo closed 5 months ago

scissorsneedfoodtoo commented 5 months ago

Checklist:

Closes https://github.com/freeCodeCamp/demo-projects/issues/597

This PR simplifies handling of the API resource protocol so resource links on the /api/pokemon endpoint only use HTTP when the project is running locally, and use HTTPS in all other cases.

I believe it's still possible for someone to set the headers to localhost:<port> when sending a request to the API, which would mean that the links at /api/pokemon would be HTTP rather than HTTPS, but I doubt it will be an issue for this project. At this point, learners should just be using fetch() without setting any headers.

lasjorg commented 5 months ago

Are you sure we need to change the protocol? The real API gives you HTTPS links, and they work fine locally. It sets Access-Control-Allow-Origin: * and we use app.use(cors()), so it should work locally with HTTPS links...shouldn't it?

scissorsneedfoodtoo commented 5 months ago

Hey @lasjorg, thanks for the additional input. That's all true.

My thinking is that it would be nice for all the links to work when running locally and in production. Currently if you're running the project locally, the output for the /api/pokemon endpoint looks like this:

{
  "count": 1302,
  "results": [
    {
      "id": 1,
      "name": "bulbasaur",
      "url": "http://localhost:3090/api/pokemon/1/"
    },
    {
      "id": 2,
      "name": "ivysaur",
      "url": "http://localhost:3090/api/pokemon/2/"
    },
    ...
  ]
}

Since all the links point to the dev API we can check that caching is working.

In production, they should point to the correct URLs, now using the expected protocol:

{
  "count": 1302,
  "results": [
    {
      "id": 1,
      "name": "bulbasaur",
      "url": "https://pokeapi-proxy.freecodecamp.rocks/api/pokemon/1/"
    },
    {
      "id": 2,
      "name": "ivysaur",
      "url": "https://pokeapi-proxy.freecodecamp.rocks/api/pokemon/2/"
    }
    ...
  ]
}

We could use a flag instead, but that might be overkill since this is the only time where the links / protocol should change. In other cases like /api/pokemon/<id-or-name>, we just return a truncated version of what the PokéAPI gives us.