Unable to use javascript function fetch() on any endpoint

Hi, I’m trying to use the Carpark API to get the options of carparksp.

This is the code I have so far to fetch from the API:

async getCarparkOptions () {
        const result = await fetch('https://api.transport.nsw.gov.au/v1/carpark', {
            method: 'GET',
            headers: {
                'Content-Type': 'application-json',
                'Accept': 'application/json',
                'Authorization': 'apikey <key>locallocal',
                'Access-Control-Allow-Origin': 'true'
            }
        });
        return result;
    }

I get a “No Access-Control-Allow-Origin header” error, I’m guessing this is because my localhost:3000 is blocked from querying the API.

Access to fetch at 'https://api.transport.nsw.gov.au/v1/carpark' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Any tips on how I could fetch from the API?

Thanks!

you can’t do it from a browser. the major browsers check with the server if your site is allowed, and the server doesn’t allow any third-party sites.

you need a CORS proxy of some sort.

1 Like