Issues using Javascript's Fetch()/Promises for the weather app

I’m currently working on my weather project, and I’m having trouble with my API call. Instead of using jquery I’ve decided to push myself and use vanilla js. I’m trying to wrap my brain around the new Fetch API, which in turn means I’m getting a bit of a crash course on Promises vs XMLHttpRequest.

My Code

I’ve gotten as far as it giving me a status code of “0”, but that doesn’t tell me much other than I personally am doing something wrong vs it being a server issue. The calls themselves are actually showing on my API usage dashboard though, so in some capacity they’re going through.

All I’m trying to do here is get the console to log the returned json. Where am I going wrong?

If all you’re doing is wrapping your head around fetch, then I’d suggest working with a simpler API that doesn’t require any authorization. GitHub’s API is great for this. Reddit also works. `https://api.github.com/users" will get you a list of Github accounts in an array, no client keys needed. A lot can go wrong with DarkSky. I have a small project you can reference here.

A couple of points:

  • Because of the way promises work, you can simply return response.json() instead of chaining then onto it. Promises are meant to be “flat”, so to speak, so you don’t need to do too much in any one function.
  • The response object has a property, ok, that will be true if the status code is between 200 and 299, inclusive. You can check that the response is good with if(response.ok)... instead of comparing the status.

Just a heads up about security. This API requires a secret key and you’ve exposed yours publicly by putting it in CodePen. I don’t know if you had to give them a CC when you signed up for an account. If you did you should definitely remove the key from your account immediately now that it’s been exposed to the public. In fact I’d revoke even if you didn’t just to be safe. Trolls could help you rack up quite a bill.

I’d recommend either developing locally or as @PortableStick recommends, using an API that doesn’t require a key for most requests.