Using GET Fetch for API Javascript worker

I need to have someone send me a URL with query variables that I want to adjust and pass to a GET api. They don’t need to redirect or anything. Just need to send a GET so the API can log it in the database.

Here is api info
https://ongage.atlassian.net/wiki/spaces/HELP/pages/13795818/API

I need to add headers that have authentication info.

I am connecting one service to another. Neither service I control.

I can do this with non CF JS worker solutions. But for some reason I cannot get this to work for me. I know the header credentials work from using a manual header changer in browser. It works just fine.

Part of the problem is I am having an issue seeing the response. Is there a better way to do this? Am I missing something simple?

addEventListener(‘fetch’, async event => {
await event.respondWith(handleRequest(event.request, event))
})

async function handleRequest(request, event) {

	const url = "https://api.ongage.net/api/contacts/add?" + querystring;

	let thing =	{ 
		method: 'get', 
		headers: new Headers({
			'x_username': '******',
			'x_password': ''******',
			'x_account_code': ''******'
	   }),
	}
	fetch(url, thing)
		.then(response => {
			if (response.status === 200) {
			  return response.json();
			} else {
			  throw new Error('Something went wrong on api server!');
			}
		})
		.then(response => {
			console.debug(response);
		}).catch(error => {
			console.error(error);
		});

}

Hi, The ‘get’ should actually be all caps 'GET'. Also you should return the fetch in order to log the console errors. I started testing this here https://cloudflareworkers.com/#4d76a90ae063bd445bcb9c1c21301a90:https://tutorial.cloudflareworkers.com/ with the testing credentials you should be able to get the response you want.

1 Like

Thanks a bunch for getting back so quick!

Still one problem. I am getting an error I was getting a bunch last night I still do not know what it means.

“Uncaught (in response) TypeError: Failed to execute function: parameter 1 is not of type ‘Response’.”

This is after I put in my credentials. But even if I did not it should still return an error right?

I had tried with the capital GET but since i was not getting anything back I was just shooting in the dark. Thanks for that easy fix.
@victoria

@bipitybopitythezopit Did you check out that demo link I sent? This is likely because you aren’t actually returning the fetch or the response in the callback. the handleRequest function needs to return either type Response or Promise<Response>

Whoops I had a typo. So the return should be

		.then(response => {
			console.debug(response);
			return new Response(response)

https://cloudflareworkers.com/?&_ga=2.47400999.1683599836.1562598898-407184045.1560540882#f8dca111d0071ff1e45261c8e2709090:https://tutorial.cloudflareworkers.com/

1 Like

Awesome, thanks so much. That is working now!