r/programminghelp • • Oct 28 '20

JavaScript fetch not getting json value

Im making a chrome extension and in my content.js I have this code

fetch('https://api.roblox.com/currency/balance')
		.then(res => res.json())
		.then((json) => {
			console.log(json);
	}).catch(err => console.error(err)); 

but it just outputs blank text and doesnt do anything when its run, its suppose to output the amount of robux the player has. It works when I tested it in my other extension.

5 Upvotes

6 comments sorted by

2

u/[deleted] Oct 28 '20

As with most non-public APIs, you need to be passing an auth token which I don't see you doing here. If this worked in another extension then that extension is doing things properly or the login was cached somehow.

1

u/[deleted] Oct 28 '20

how would i do that? this extension has all the same permission things, its exactly the same, would it make a difference if I did it in the context.js (Thats where im doing it) instead of in the code for the popup?

EDIT: reddit glitched and posted it 4 times sorry

1

u/Gyerfry Oct 30 '20

Generally, you'd either receive an auth key as part of the HTTP response upon logging in, or have one provided in your user settings if the API is meant for persistent systems. Either way, you have to put it in the headers of the fetch request.

1

u/Gyerfry Oct 29 '20

Something to note from the documentation for fetch:

The fetch specification differs from jQuery.ajax() in three main ways:

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

So there may be errors that you aren't seeing.

1

u/[deleted] Oct 30 '20

How would I find out what they are?

1

u/Gyerfry Oct 30 '20

Try using jQuery.ajax() instead of fetch().

1

u/[deleted] Oct 31 '20

Can you do that with chrome extensions?