How can do you make an API call without a proxy server? - javascript

I have a URL for a Google Places API that returns the proper json, but when I use fetch, I get this error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Here's my code
fetch(url, {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin': '*'
}
})
.then(res => res.json())
.then(data => console.log('data', data))
.catch(e => console.log('e', e))
The reason why I don't want to make a proxy server is that I'm using a static site hosting service (and it's just more work to make a proxy server). I figured that if I already have a working url, it should be pretty simple to just fetch the json from that url. This is for a React app (made with create-react-app).

Related

Fetch request is being being blocked by CORS policy?

I'm making an API request to the Beehiiv API, to get my list of publications.
Inside my React component, I've set up a fetch request to the API. However the request is being being blocked by the CORS policy. Request code below:
async function makeRequest(){
const fetchOptions = {
method: 'get',
headers: {
"X-ApiKey": '<MY API KEY>',
"Content-Type": "application/json",
"Access-Control-Allow-Origin" : '*'
},
}
fetch('https://api.beehiiv.com/v1/publications', fetchOptions).then( response => response.json() )
.then( data => console.log(data) )
}
makeRequest();
The response in the console is as follows:
Access to fetch at 'https://api.beehiiv.com/v1/publications' 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.
Calling other API's does not seem to result in getting blocked.
Any ideas on why this may be happening? Please let me know! Thanks!
From beehiiv API documentation:
API keys are considered sensitive data and should not be shared with anyone. Be careful not to expose the API key in your source code or any other public location (including front-end code).
The API isn't supposed to be called from the frontend.
You need to make AJAX requests to your own server, which then calls the API, so the API key isn't exposed.

Instagram public API (/?__a=1) works, but only sometimes

So I'm trying to pull some instagram images using the public API:
const url = `https://www.instagram.com/${username}/?__a=1`;
fetch(url)
.then(response => response.json())
.then(data => {
prepareImages(data['graphql']['user']['edge_owner_to_timeline_media']['edges'])
})
.catch(error => console.log(error));
This works perfectly fine 4 times out of 5. However, once in a while, I get an error saying:
Access to fetch at 'https://www.instagram.com/instagram/?__a=1' from origin 'https://test.com' has been blocked by CORS policy: 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.
I have tried changing the mode to 'no-cors', but that just leads to an empty response. Do you guys think they just block the request sometimes to prevent spamming?
you can try using graphql by using query hash or query id more information in this post Instagram ?__a=1 url not working anymore & problems with graphql/query to get data

Has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin

I'm running my Vue app locally from http://localhost:8080 and I keep getting a slew of CORS errors, I've added the Access-Control-Allow-Origin header as seen blow but keep getting the following warning:
' from origin 'http://localhost:8080' 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.
const graphCall = () => {
let tokenOptions = {
method: 'POST',
uri: 'https://login.microsoftonline.com/**key**/oauth2/v2.0/token',
headers: {
'Access-Control-Allow-Origin': 'http://localhost:8080',
'contentType': 'application/x-www-form-urlencoded'
},
form: {
grant_type: VUE_APP_GRANT_TYPE,
client_secret: VUE_APP_CLIENT_SECRET,
scope: VUE_APP_SCOPE,
client_id: VUE_APP_CLIENT_ID
}
};
return rp(tokenOptions)
.then(data => {
console.log(data)
}).catch((err) => {
console.log(err);
});
};
I've tried adding mode: 'no-cors' but just get the following - Error: Invalid value for opts.mode
I've also tried '*' as the access control origin but to no avail.
Is there a way through this CORS nightmare as we need to make this call to retrieve a key!
The server has to allow your origin, in this case http://localhost:8080. Often in scenarios where you are interacting with a provider, in the admin portal where you create the tokens, you also have to specify the domain from which you intend on calling it from.
If this is not the case you may be triggering CORS because you are using a header not on the CORS safe list.
https://fetch.spec.whatwg.org/#cors-safelisted-request-header
Access-Control-Allow-Origin is normally the header supplied by the server on a response, it is not meant to be sent on the request.
The following link helped me understand CORS better.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Do note that allowing the origin of * is fine for development but not recommended for production applications.

CORSS with proxy url

I am making a react application where I use an API. However, I couldn't make the API work and I opted for CROSS, using a proxy URL (https://yacdn.org/proxy/). Now I can retrieve my desired information from the API but after some time my application crashes.
I get an error saying:
Access to fetch at 'https://yacdn.org/proxy/https://apps.des.qld.gov.au/species/?op=getspecies&kingdom=animals&family=Macropodidae' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.
I tried using mode: 'no-cors'. I am not allowed to use Chrome-extension and was told to come up with a backend solution that just forwards (proxies) the call to the API and returns the result
How can I solve this? Any hint will be appreciated.
You can use fetch to achieve this:
fetch('https://cors.io/?https://apps.des.qld.gov.au/species/?op=getspecies&kingdom=animals&family=Macropodidae',
{
method: 'GET'
})
.then(res => {
res.text().then((s) => console.log(JSON.parse(s)))
})
.catch(error => {
// Handle your error
throw new Error('Failed while checking data from au services:' + error)
})
Use this proxy server:
https://cors.io/?...
And also for the response is important to convert into JSON object:
res.text().then((s) => console.log(JSON.parse(s)))
Hope it help you.

Google Maps Place request from browser

Trying to get a request from a React app to Google Maps API working but getting CORS issues. Google says it supports CORS but not sure how to make the right request to be able to retrieve place data.
const src = `https://maps.googleapis.com/maps/api/place/details/json?key=${GOOGLE_API_KEY}&placed=${id}&fields=formatted_phone_number`
const headers = {
'Access-Control-Allow-Origin' : '*'
}
fetch(src, { mode: 'cors', headers: headers }).then(response => console.log(response))
The src itself is fine but getting this issue:
Failed to load
https://maps.googleapis.com/maps/api/place/details/json?key=(keyRemoved)&placed=(placeRemoved)&fields=formatted_phone_number:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8000' is therefore not allowed
access.
I think your best bet is to use the Places service in the Javascript API
https://developers.google.com/maps/documentation/javascript/reference/3.exp/places-service#PlacesService

Categories